<?php

namespace App\Service\OpenShop\FeishuMini;

use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use App\Library\Common\DateTool;
use App\Models\Common\CityResidencePriceModel;
use App\Models\Common\CityTerritorialBoundaryModel;
use App\Models\Common\ConfigModel;
use App\Models\Common\FileTranscodingJobModel;
use App\Models\Common\MapNationalBrandShopModel;
use App\Models\Common\MapNationalCommunityModel;
use App\Models\Common\MapNationalIndustrialParkModel;
use App\Models\Common\MapNationalStreetModel;
use App\Models\Common\MapNationalUniversitiesModel;
use App\Models\Common\MapTownshipPlanAreaModel;
use App\Models\Common\ResourcesModel;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\Common\SiteLocationMallModel;
use App\Models\OpenShop\Common\WangguiBrowsingHistoryModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\OpenShop\Wanggui\WangguiSiteDistrictModel;
use App\Models\Wanggui\CustomerDepartmentTaskModel;
use App\Service\BaseService;
use App\Service\Common\UploadTranscoding;
use App\Service\Kms\Task\UserRoleService;
use App\Service\OpenShop\Feishu\ConfigService;
use App\Service\OpenShop\SiteLocation\GuanyuanDataService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\WaiMai\WaiMaiAnalysisService;
use Carbon\Carbon;
use Guanguans\Notify\Factory;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redis;
use Overtrue\Pinyin\Pinyin;
use function Symfony\Component\Translation\t;

class ProgrammingService extends BaseService
{
    public static function list(
        $type, $subType, $city, $district, $lng, $lat, $pageNum, $pageSize, $sort, $status,
        $openScore, $settleStatus, $grade, $chosen, $name, $ids = [], $orderNoArr = [], $userInfo = [], $isKms = false,
        $isOwn = false, int $provinceCode = 0, int $cityCode = 0, int $districtCode = 0, int $searchId = 0
    ): array
    {
        $city    = self::blurMatchCity($city);
        $history = [];
        $data    = $statusArr = $statusData = $provinceCodes = $cityCodes = $districtCodes = $userInfos = [];
        $role    = 0;
        if ($isKms) {
            $city = $district = '';//运营新接口用省市区code查询
            if (mb_strlen($status)) {
                $statusArr = explode(',', $status);
                foreach ($statusArr as $v) {
                    $temp = ProgrammingEnum::WG_AND_TASK_STATUS_MAPPING[$v] ?? [];
                    if ($temp) {
                        $statusData = array_merge($statusData, $temp);
                    }
                }
                $status = '';
            }

            // 查询用户身份权限
            $getUserRole  = UserRoleService::getUserRole($userInfo['userId']);
            $role         = $getUserRole['role'] ?? UserRoleService::ROLE_SPECIAL_NO_ACCESS;
            $allArea      = $getUserRole['userResponsibleArea']['all'] ?? false;
            $branchOffice = $getUserRole['homeBranchOffice']['branchOffice'] ?? [];

            if (!$allArea && $branchOffice  && !$provinceCode && !$cityCode && !$districtCode) {//获取对应分公司id
                $branchIds     = array_column($branchOffice, 'id');
                $getRegionInfo = OpenShopOrganizationRegionMappingModel::getRegionInfo($branchIds);
                if ($getRegionInfo) {
                    $provinceCodes = array_column($getRegionInfo, 'provinceCode');
                }
            }
            if ($allArea || in_array($role, [UserRoleService::ROLE_BASE_KAM])) {
                $provinceCodes = $cityCodes = $districtCodes = [];
            }

//            $userInfos = KmsUser::getUserInfo([], '选址开发中心');//大客户部用户信息
        } else {

            if (mb_strlen($sort) && $sort == 2 && (!mb_strlen($lng) || !mb_strlen($lat))) {
                self::throwErr('请打开手机定位');
            }
        }
        if ($provinceCode) {
            $provinceCodes = [$provinceCode];
        }
        if ($cityCode) {
            $cityCodes = [$cityCode];
        }
        if ($districtCode) {
            $districtCodes = [$districtCode];
        }
        switch ($type) {
            case ProgrammingEnum::PROGRAMMING_MALL:  //商场网规
                $paginator = SiteLocationMallModel::query()
                    ->when($isKms, function ($query) {
                        $query->leftJoin('customer_department_task', 'customer_department_task.wgNumber', '=', 'site_location_mall.wgNumber');
                    }
                    )
                    ->when(
                        ($isOwn || $statusArr) && $isKms, function ($query) use ($statusData, $statusArr, $isOwn, $userInfo) {
                        $query->when(
                            $isOwn && $userInfo, function ($query) use ($userInfo) {
                            $query->where('customer_department_task.assignId', $userInfo['userId'] ?? 0);//只看自己的
                        }
                        )->when(
                            $statusArr, function ($query) use ($statusData, $statusArr) {
                            $query->where(
                                function ($query) use ($statusData, $statusArr) {
                                    $query->when(
                                        $statusData, function ($query) use ($statusData) {
                                        $query->whereIn('customer_department_task.projectPhase', $statusData);//关联项目阶段状态
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && $statusData, function ($query) use ($statusArr) {
                                        $query->orWhere(
                                            function ($query) use ($statusArr) {
                                                $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                                ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                            }
                                        );
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && !$statusData, function ($query) use ($statusArr) {
                                        $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                        ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                    }
                                    );
                                }
                            );
                        }
                        );
                    }
                    )
                    ->where('site_location_mall.grade', '>', 0)
                    ->when($searchId, function ($query) use ($searchId) {
                        $query->where('site_location_mall.id', $searchId);
                    })
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('site_location_mall.city', 'like', "%$city%");
                    })
                    ->when(mb_strlen($district), function ($query) use ($district) {
                        $query->where('site_location_mall.district', 'like', "%$district%");
                    })
                    ->when(
                        $provinceCodes, function ($query) use ($provinceCodes) {
                        $query->whereIn('site_location_mall.provinceCode', $provinceCodes);
                    }
                    )
                    ->when(
                        $cityCodes, function ($query) use ($cityCodes) {
                        $query->whereIn('site_location_mall.cityCode', $cityCodes);
                    }
                    )
                    ->when(
                        $districtCodes, function ($query) use ($districtCodes) {
                        $query->whereIn('site_location_mall.districtCode', $districtCodes);
                    }
                    )
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('site_location_mall.status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('site_location_mall.status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($openScore), function ($query) use ($openScore) {
                        $statusArr = explode(',', $openScore);
                        $query->whereBetween('site_location_mall.status', $statusArr);
                    })
                    ->when(count($ids), function ($query) use ($ids) {
                        $query->whereIn('site_location_mall.id', $ids);
                    })
                    ->when(count($orderNoArr), function ($query) use ($orderNoArr) {
                        $query->whereIn('site_location_mall.wgNumber', $orderNoArr);
                    })
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where(function ($q) use ($name) {
                            $q->where('site_location_mall.mallName', 'like', "%$name%")->orWhere('site_location_mall.address', 'like', "%$name%");
                        });
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('site_location_mall.settle', $settleStatus);
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('site_location_mall.grade', $gradeArr);
                    })
                    ->when(mb_strlen($chosen), function ($query) use ($chosen) {
                        $chosenArr = explode(',', $chosen);
                        if (count($chosenArr) == 1) {
                            if ($chosen == 1) {
                                $query->where('site_location_mall.topList', '!=', '');
                            }
                            if ($chosen == 2) {
                                $query->where('site_location_mall.topList', '');
                            }
                        }
                    })
                    ->when(1, function ($query) use ($sort, $lng, $lat) {
                        switch ($sort) {
                            case ProgrammingEnum::MALL_SORT_GRADE:
                                $query->orderBy('site_location_mall.grade', 'desc');
                                break;
                            case ProgrammingEnum::MALL_SORT_NEAR:
                                $query->selectRaw("site_location_mall.*, ST_Distance_Sphere(POINT(`lng`, `lat`), POINT(?, ?)) AS distance", [$lng, $lat])->orderBy("distance");
                                break;
                            case ProgrammingEnum::MALL_SORT_MAX_SHOP_COUNT:
                                $query->orderBy('site_location_mall.shopTotalCount', 'desc');
                                break;
                            case ProgrammingEnum::MALL_SORT_FOOT:
                                $query->orderBy('site_location_mall.foodRatio', 'desc');
                                break;
                            default:
                                $query->orderBy("site_location_mall.grade", 'desc');
                        }
                    })
                    ->with(['logRel.resourceRelByCover', 'resourceWithMapRel', 'siteTaskRel'])
                    ->paginate($pageSize, ['site_location_mall.*'], 'page', $pageNum);

                $userInfos = [];
                if ($isKms) {
                    $assignIds = array_unique(array_column(array_column($paginator->items(), 'siteTaskRel'), 'assignId')) ?? [];//开发经理
                    $userInfos = KmsUser::getUserInfo($assignIds);                                                              //用户信息
                }
                $data      = [
                    'count'    => $paginator->total(),
                    'list'     => $history[] = array_map(function (SiteLocationMallModel $siteLocation) use ($isKms, $userInfo, $userInfos) {
                        $cover = (string)optional($siteLocation->resourceWithMapRel)->url ? picturePath($siteLocation->resourceWithMapRel->url) : '';
                        if ($siteLocation->logRel->count() != 0) {
                            foreach ($siteLocation->logRel->toArray() as $log) {
                                foreach ($log['resource_rel_by_cover'] as $resource) {
                                    $type = json_decode($resource['extra'], true)['type'] ?? '-';
                                    if ($resource['name'] == ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION && $type == 'image') {
                                        $cover = picturePath($resource['url']);
                                    }
                                }
                            }
                        }
                        $distance = '';
                        if ($siteLocation->distance) {
                            if (ceil($siteLocation->distance) > 999) {
                                $distance = round(ceil($siteLocation->distance) / 1000, 1) . 'km';
                            } else {
                                $distance = ceil($siteLocation->distance) . 'm';
                            }
                        }

                        // 判断是否显示堪址按钮
                        $siteTaskButton = false;
                        if ((int)optional($siteLocation->siteTaskRel)->assignId > 0 && (int)optional($siteLocation->siteTaskRel)->assignId == ($userInfo['userId'] ?? 0)) {
                            $siteTaskButton = true;
                        }
                        $status     = $siteLocation->status;
                        $statusText = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$siteLocation->status] ?? '-';
                        $grade      = OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_SIFT_MAPPING[$siteLocation->grade] ?? '-';
                        if ($isKms) {
                            $projectPhase     = optional($siteLocation->siteTaskRel)->projectPhase ?? 0;
                            $conversionStatus = self::conversionStatus($projectPhase);
                            $status           = $conversionStatus['status'];
                            $statusText       = $conversionStatus['statusText'];
                            $grade            = mb_substr($grade, 0, (mb_strlen($grade) - 1)) . '商';
                        }

                        return [
                            'id'         => $siteLocation->id,
                            'cover'      => $cover ?: 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                            'name'       => $siteLocation->mallName,
                            'province'   => $siteLocation->province,
                            'city'       => $siteLocation->city,
                            'district'   => $siteLocation->district,
                            'recommendFloor' => $siteLocation->recommendFloor,  //推荐楼层
                            'distance'   => $distance,
                            'area'       => $siteLocation->area,
                            'address'    => $siteLocation->address,
                            'status'     => $status,
                            'statusText' => $statusText,
                            'grade'      => $grade,
                            'settleIn'   => $siteLocation->settle ? '已入驻' : '',
                            'rank'       => mb_strlen($siteLocation->topList) ? [$siteLocation->topList] : [],
                            'wgNumber'   => $siteLocation->wgNumber,
                            'type'       => ProgrammingEnum::PROGRAMMING_MALL,
                            // 客户部堪址任务
                            'siteTaskButton'               => $siteTaskButton,
                            'siteTaskRelationId'           => (int)optional($siteLocation->siteTaskRel)->id,
                            'siteTaskRelationAssignId'     => (int)optional($siteLocation->siteTaskRel)->assignId,                  //指派给
                            'siteTaskRelationUserName'     => $userInfos[optional($siteLocation->siteTaskRel)->assignId ?? 0] ?? '',//用户名称
                            'siteTaskRelationAssignTime'   => optional($siteLocation->siteTaskRel)->assignTime ?
                                date('Y-m-d', optional($siteLocation->siteTaskRel)->assignTime) : '',  //指派时间
                            'siteTaskRelationFollowUpTime' => optional($siteLocation->siteTaskRel)->followUpTime ?
                                date('Y-m-d', optional($siteLocation->siteTaskRel)->followUpTime) : '',//最新跟进时间
                            'detail'     => [
                                [
                                    'name'  => '店铺总数',
                                    'value' => $siteLocation->shopTotalCount,
                                ], [
                                    'name'  => '美食店铺占比',
                                    'value' => $siteLocation->foodRatio ? ($siteLocation->foodRatio * 100 . '%') : 0,
                                ], [
                                    'name'  => '夸父门店数',
                                    'value' => $siteLocation->shopNum,
                                ]
                            ]
                        ];
                    }, $paginator->items()),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                ];
                break;
            case ProgrammingEnum::PROGRAMMING_STREET:  //街道网规
                $paginator = MapNationalStreetModel::query()
                    ->when($isKms, function ($query) {
                        $query->leftJoin('customer_department_task', 'customer_department_task.wgNumber', '=', 'map_national_streets.wgNumber');
                    }
                    )
                    ->when(
                        ($isOwn || $statusArr) && $isKms, function ($query) use ($statusData, $statusArr, $isOwn, $userInfo) {
                        $query->when(
                            $isOwn, function ($query) use ($userInfo) {
                            $query->where('customer_department_task.assignId', $userInfo['userId'] ?? 0);//只看自己的
                        }
                        )->when(
                            $statusArr, function ($query) use ($statusArr, $statusData) {
                            $query->where(
                                function ($query) use ($statusData, $statusArr) {
                                    $query->when(
                                        $statusData, function ($query) use ($statusData) {
                                        $query->whereIn('customer_department_task.projectPhase', $statusData);//关联项目阶段状态
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && $statusData, function ($query) use ($statusArr) {
                                        $query->orWhere(
                                            function ($query) use ($statusArr) {
                                                $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                                ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                            }
                                        );
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && !$statusData, function ($query) use ($statusArr) {
                                        $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                        ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                    }
                                    );
                                }
                            );
                        }
                        );
                    }
                    )
                    ->when($searchId, function ($query) use ($searchId) {
                        $query->where('map_national_streets.id', $searchId);
                    })
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('map_national_streets.city', 'like', "%$city%");
                    })
                    ->when(mb_strlen($district), function ($query) use ($district) {
                        $query->where('map_national_streets.district', 'like', "%$district%");
                    })
                    ->when(
                        $provinceCodes, function ($query) use ($provinceCodes) {
                        $query->whereIn('map_national_streets.provinceCode', $provinceCodes);
                    }
                    )
                    ->when(
                        $cityCodes, function ($query) use ($cityCodes) {
                        $query->whereIn('map_national_streets.cityCode', $cityCodes);
                    }
                    )
                    ->when(
                        $districtCodes, function ($query) use ($districtCodes) {
                        $query->whereIn('map_national_streets.districtCode', $districtCodes);
                    }
                    )
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('map_national_streets.address', 'like', "%$name%");
                    })
                    ->when(count($ids), function ($query) use ($ids) {
                        $query->whereIn('map_national_streets.id', $ids);
                    })
                    ->when(count($orderNoArr), function ($query) use ($orderNoArr) {
                        $query->whereIn('map_national_streets.wgNumber', $orderNoArr);
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('map_national_streets.settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_streets.status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_streets.status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($openScore), function ($query) use ($openScore) {
                        $statusArr = explode(',', $openScore);
                        $query->whereBetween('map_national_streets.status', $statusArr);
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('map_national_streets.grade', $gradeArr);
                    })
                    ->when(1, function ($query) use ($sort, $lng, $lat) {
                        switch ($sort) {
                            case ProgrammingEnum::STREET_SORT_GRADE:
                                $query->orderBy("map_national_streets.grade", 'desc');
                                break;
                            case ProgrammingEnum::STREET_SORT_NEAR:
                                $query->selectRaw("map_national_streets.*, ST_Distance_Sphere(POINT(`lng`, `lat`), POINT({$lng}, {$lat})) AS distance")->orderBy("distance");
                                break;
                            default:
                                $query->orderBy("map_national_streets.grade", 'desc');
                        }
                    })
                    ->with(['logRel.resourceRelByCover', 'resourceWithMapRel', 'siteTaskRel'])
                    ->paginate($pageSize, ['map_national_streets.*'], 'page', $pageNum);

                $userInfos = [];
                if ($isKms) {
                    $assignIds = array_unique(array_column(array_column($paginator->items(), 'siteTaskRel'), 'assignId')) ?? [];//开发经理
                    $userInfos = KmsUser::getUserInfo($assignIds);                                                              //用户信息
                }
                $data      = [
                    'count'    => $paginator->total(),
                    'list'     => $history[] = array_map(function (MapNationalStreetModel $mapNationalStreetModel) use ($isKms, $userInfo, $userInfos){
                        if (mb_strpos($mapNationalStreetModel->address, $mapNationalStreetModel->name) === false) {
                            $name = $mapNationalStreetModel->name;
                        } else {
                            $name = mb_substr($mapNationalStreetModel->address, mb_strpos($mapNationalStreetModel->address, $mapNationalStreetModel->name));
                        }
                        $cover = (string)optional($mapNationalStreetModel->resourceWithMapRel)->url ? picturePath($mapNationalStreetModel->resourceWithMapRel->url) : '';
                        if ($mapNationalStreetModel->logRel->count() != 0) {
                            foreach ($mapNationalStreetModel->logRel->toArray() as $log) {
                                foreach ($log['resource_rel_by_cover'] as $resource) {
                                    $type = json_decode($resource['extra'], true)['type'] ?? '-';
                                    if ($resource['name'] == ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION && $type == 'image') {
                                        $cover = picturePath($resource['url']);
                                    }
                                }
                            }
                        }
                        $distance = '';
                        if ($mapNationalStreetModel->distance) {
                            if (ceil($mapNationalStreetModel->distance) > 999) {
                                $distance = round(ceil($mapNationalStreetModel->distance) / 1000, 1) . 'km';
                            } else {
                                $distance = ceil($mapNationalStreetModel->distance) . 'm';
                            }
                        }

                        // 判断是否显示堪址按钮
                        $siteTaskButton = false;
                        if ((int)optional($mapNationalStreetModel->siteTaskRel)->assignId > 0 && (int)optional($mapNationalStreetModel->siteTaskRel)->assignId == ($userInfo['userId'] ?? 0)) {
                            $siteTaskButton = true;
                        }
                        $status     = $mapNationalStreetModel->status;
                        $statusText = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$mapNationalStreetModel->status] ?? '-';
                        $grade      = ProgrammingEnum::GRADE_MAPPING[$mapNationalStreetModel->grade] ?? '-';
                        if ($isKms) {
                            $projectPhase     = optional($mapNationalStreetModel->siteTaskRel)->projectPhase ?? 0;
                            $conversionStatus = self::conversionStatus($projectPhase);
                            $status           = $conversionStatus['status'];
                            $statusText       = $conversionStatus['statusText'];
                            $grade            = mb_substr($grade, 0, (mb_strlen($grade) - 1)) . '街';
                        }

                        return [
                            'id'         => $mapNationalStreetModel->id,
                            'cover'      => $cover ?: 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                            'name'       => $name,
                            'province'   => $mapNationalStreetModel->province,
                            'city'       => $mapNationalStreetModel->city,
                            'district'   => $mapNationalStreetModel->district,
                            'distance'   => $distance,
                            'area'       => '',
                            'address'    => $mapNationalStreetModel->address,
                            'status'     => $status,
                            'statusText' => $statusText,
                            'grade'      => $grade,
                            'settleIn'   => $mapNationalStreetModel->settle ? '已入驻' : '',
                            'rank'       => [],
                            'wgNumber'   => $mapNationalStreetModel->wgNumber,
                            'type'       => ProgrammingEnum::PROGRAMMING_STREET,
                            // 客户部堪址任务
                            'siteTaskButton'               => $siteTaskButton,
                            'siteTaskRelationId'           => (int)optional($mapNationalStreetModel->siteTaskRel)->id,
                            'siteTaskRelationAssignId'     => (int)optional($mapNationalStreetModel->siteTaskRel)->assignId,    //指派给
                            'siteTaskRelationUserName'     => $userInfos[optional($mapNationalStreetModel->siteTaskRel)->assignId ?? 0] ?? '',//用户名称
                            'siteTaskRelationAssignTime'   => optional($mapNationalStreetModel->siteTaskRel)->assignTime ?
                                date('Y-m-d', optional($mapNationalStreetModel->siteTaskRel)->assignTime) : '',  //指派时间
                            'siteTaskRelationFollowUpTime' => optional($mapNationalStreetModel->siteTaskRel)->followUpTime ?
                                date('Y-m-d', optional($mapNationalStreetModel->siteTaskRel)->followUpTime) : '',//最新跟进时间
                            'detail'     => [
                                [
                                    'name'  => '夸父门店数',
                                    'value' => $mapNationalStreetModel->shopNum,
                                ]
                            ]
                        ];
                    }, $paginator->items()),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                ];
                break;
            case ProgrammingEnum::PROGRAMMING_COMMUNITY:  //社区网规
                $paginator = MapNationalCommunityModel::query()
                    ->when($isKms, function ($query) {
                        $query->leftJoin('customer_department_task', 'customer_department_task.wgNumber', '=', 'map_national_communities.wgNumber');
                    }
                    )
                    ->when(
                        ($isOwn || $statusArr) && $isKms, function ($query) use ($statusData, $statusArr, $isOwn, $userInfo) {
                        $query->when(
                            $isOwn, function ($query) use ($userInfo) {
                            $query->where('customer_department_task.assignId', $userInfo['userId'] ?? 0);//只看自己的
                        }
                        )->when(
                            $statusArr, function ($query) use ($statusArr, $statusData) {
                            $query->where(
                                function ($query) use ($statusData, $statusArr) {
                                    $query->when(
                                        $statusData, function ($query) use ($statusData) {
                                        $query->whereIn('customer_department_task.projectPhase', $statusData);//关联项目阶段状态
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && $statusData, function ($query) use ($statusArr) {
                                        $query->orWhere(
                                            function ($query) use ($statusArr) {
                                                $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                                ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                            }
                                        );
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && !$statusData, function ($query) use ($statusArr) {
                                        $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                        ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                    }
                                    );
                                }
                            );
                        }
                        );
                    }
                    )
                    ->when($searchId, function ($query) use ($searchId) {
                        $query->where('map_national_communities.id', $searchId);
                    })
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('map_national_communities.city', 'like', "%$city%");
                    })
                    ->when(mb_strlen($district), function ($query) use ($district) {
                        $query->where('map_national_communities.district', 'like', "%$district%");
                    })
                    ->when(
                        $provinceCodes, function ($query) use ($provinceCodes) {
                        $query->whereIn('map_national_communities.provinceCode', $provinceCodes);
                    }
                    )
                    ->when(
                        $cityCodes, function ($query) use ($cityCodes) {
                        $query->whereIn('map_national_communities.cityCode', $cityCodes);
                    }
                    )
                    ->when(
                        $districtCodes, function ($query) use ($districtCodes) {
                        $query->whereIn('map_national_communities.districtCode', $districtCodes);
                    }
                    )
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('map_national_communities.address', 'like', "%$name%");
                    })
                    ->when(count($ids), function ($query) use ($ids) {
                        $query->whereIn('map_national_communities.id', $ids);
                    })
                    ->when(count($orderNoArr), function ($query) use ($orderNoArr) {
                        $query->whereIn('map_national_communities.wgNumber', $orderNoArr);
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('map_national_communities.settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_communities.status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_communities.status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($openScore), function ($query) use ($openScore) {
                        $statusArr = explode(',', $openScore);
                        $query->whereBetween('map_national_communities.status', $statusArr);
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('map_national_communities.grade', $gradeArr);
                    })
                    ->when(1, function ($query) use ($sort, $lng, $lat) {
                        switch ($sort) {
                            case ProgrammingEnum::STREET_SORT_GRADE:
                                $query->orderBy("map_national_communities.grade", 'desc');
                                break;
                            case ProgrammingEnum::STREET_SORT_NEAR:
                                $query->selectRaw("map_national_communities.*, ST_Distance_Sphere(POINT(`lng`, `lat`), POINT({$lng}, {$lat})) AS distance")->orderBy("distance");
                                break;
                            default:
                                $query->orderBy("map_national_communities.grade", 'desc');
                        }
                    })
                    ->with(['logRel.resourceRelByCover', 'resourceWithMapRel', 'siteTaskRel'])
                    ->paginate($pageSize, ['map_national_communities.*'], 'page', $pageNum);

                $userInfos = [];
                if ($isKms) {
                    $assignIds = array_unique(array_column(array_column($paginator->items(), 'siteTaskRel'), 'assignId')) ?? [];//开发经理
                    $assignIds = array_values($assignIds);
                    $userInfos = KmsUser::getUserInfo($assignIds);                                                              //用户信息
                }
                $data      = [
                    'count'    => $paginator->total(),
                    'list'     => $history[] = array_map(function (MapNationalCommunityModel $mapNationalCommunityModel) use ($isKms, $userInfo, $userInfos){
                        if (mb_strpos($mapNationalCommunityModel->address, $mapNationalCommunityModel->name) === false) {
                            $name = $mapNationalCommunityModel->name;
                        } else {
                            $name = mb_substr($mapNationalCommunityModel->address, mb_strpos($mapNationalCommunityModel->address, $mapNationalCommunityModel->name));
                        }
                        $cover = (string)optional($mapNationalCommunityModel->resourceWithMapRel)->url ? picturePath($mapNationalCommunityModel->resourceWithMapRel->url) : '';
                        if ($mapNationalCommunityModel->logRel->count() != 0) {
                            foreach ($mapNationalCommunityModel->logRel->toArray() as $log) {
                                foreach ($log['resource_rel_by_cover'] as $resource) {
                                    $type = json_decode($resource['extra'], true)['type'] ?? '-';
                                    if ($resource['name'] == ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION && $type == 'image') {
                                        $cover = picturePath($resource['url']);
                                    }
                                }
                            }
                        }
                        $distance = '';
                        if ($mapNationalCommunityModel->distance) {
                            if (ceil($mapNationalCommunityModel->distance) > 999) {
                                $distance = round(ceil($mapNationalCommunityModel->distance) / 1000, 1) . 'km';
                            } else {
                                $distance = ceil($mapNationalCommunityModel->distance) . 'm';
                            }
                        }

                        // 判断是否显示堪址按钮
                        $siteTaskButton = false;
                        if ((int)optional($mapNationalCommunityModel->siteTaskRel)->assignId > 0 && (int)optional($mapNationalCommunityModel->siteTaskRel)->assignId == ($userInfo['userId'] ?? 0)) {
                            $siteTaskButton = true;
                        }
                        $status     = $mapNationalCommunityModel->status;
                        $statusText = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$mapNationalCommunityModel->status] ?? '-';
                        $grade      = ProgrammingEnum::GRADE_MAPPING[$mapNationalCommunityModel->grade] ?? '-';
                        if ($isKms) {
                            $projectPhase     = optional($mapNationalCommunityModel->siteTaskRel)->projectPhase ?? 0;
                            $conversionStatus = self::conversionStatus($projectPhase);
                            $status           = $conversionStatus['status'];
                            $statusText       = $conversionStatus['statusText'];
                            $grade            = mb_substr($grade, 0, (mb_strlen($grade) - 1)) . '街';
                        }

                        return [
                            'id'         => $mapNationalCommunityModel->id,
                            'cover'      => $cover ?: 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                            'name'       => $name,
                            'province'   => $mapNationalCommunityModel->province,
                            'city'       => $mapNationalCommunityModel->city,
                            'district'   => $mapNationalCommunityModel->district,
                            'distance'   => $distance,
                            'area'       => '',
                            'address'    => $mapNationalCommunityModel->address,
                            'status'     => $status,
                            'statusText' => $statusText,
                            'grade'      => $grade,
                            'settleIn'   => $mapNationalCommunityModel->settle ? '已入驻' : '',
                            'rank'       => [],
                            'wgNumber'   => $mapNationalCommunityModel->wgNumber,
                            'type'       => ProgrammingEnum::PROGRAMMING_COMMUNITY,
                            // 客户部堪址任务
                            'siteTaskButton'               => $siteTaskButton,
                            'siteTaskRelationId'           => (int)optional($mapNationalCommunityModel->siteTaskRel)->id,
                            'siteTaskRelationAssignId'     => (int)optional($mapNationalCommunityModel->siteTaskRel)->assignId,    //指派给
                            'siteTaskRelationUserName'     => $userInfos[optional($mapNationalCommunityModel->siteTaskRel)->assignId ?? 0] ?? '',//用户名称
                            'siteTaskRelationAssignTime'   => optional($mapNationalCommunityModel->siteTaskRel)->assignTime ?
                                date('Y-m-d', optional($mapNationalCommunityModel->siteTaskRel)->assignTime) : '',  //指派时间
                            'siteTaskRelationFollowUpTime' => optional($mapNationalCommunityModel->siteTaskRel)->followUpTime ?
                                date('Y-m-d', optional($mapNationalCommunityModel->siteTaskRel)->followUpTime) : '',//最新跟进时间
                            'detail'     => [
                                [
                                    'name'  => '夸父门店数',
                                    'value' => $mapNationalCommunityModel->shopNum,
                                ]
                            ]
                        ];
                    }, $paginator->items()),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                ];
                break;
            case ProgrammingEnum::PROGRAMMING_TOWN:  //乡镇网规
                $paginator = MapTownshipPlanAreaModel::query()
                    ->when($isKms, function ($query) {
                        $query->leftJoin('customer_department_task', 'customer_department_task.wgNumber', '=', 'map_township_plan_area.wgNumber');
                    }
                    )
                    ->when(
                        ($isOwn || $statusArr) && $isKms, function ($query) use ($statusData, $statusArr, $isOwn, $userInfo) {
                        $query->when(
                            $isOwn, function ($query) use ($userInfo) {
                            $query->where('customer_department_task.assignId', $userInfo['userId'] ?? 0);//只看自己的
                        }
                        )->when(
                            $statusArr, function ($query) use ($statusData, $statusArr) {
                            $query->where(
                                function ($query) use ($statusData, $statusArr) {
                                    $query->when(
                                        $statusData, function ($query) use ($statusData) {
                                        $query->whereIn('customer_department_task.projectPhase', $statusData);//关联项目阶段状态
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && $statusData, function ($query) use ($statusArr) {
                                        $query->orWhere(
                                            function ($query) use ($statusArr) {
                                                $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                                ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                            }
                                        );
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && !$statusData, function ($query) use ($statusArr) {
                                        $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                        ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                    }
                                    );
                                }
                            );
                        }
                        );
                    }
                    )
                    ->when($searchId, function ($query) use ($searchId) {
                        $query->where('map_township_plan_area.id', $searchId);
                    })
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('map_township_plan_area.city', 'like', "%$city%");
                    })
                    ->when(mb_strlen($district), function ($query) use ($district) {
                        $query->where('map_township_plan_area.district', 'like', "%$district%");
                    })
                    ->when(
                        $provinceCodes, function ($query) use ($provinceCodes) {
                        $query->whereIn('map_township_plan_area.provinceCode', $provinceCodes);
                    }
                    )
                    ->when(
                        $cityCodes, function ($query) use ($cityCodes) {
                        $query->whereIn('map_township_plan_area.cityCode', $cityCodes);
                    }
                    )
                    ->when(
                        $districtCodes, function ($query) use ($districtCodes) {
                        $query->whereIn('map_township_plan_area.districtCode', $districtCodes);
                    }
                    )
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('map_township_plan_area.address', 'like', "%$name%");
                    })
                    ->when(count($ids), function ($query) use ($ids) {
                        $query->whereIn('map_township_plan_area.id', $ids);
                    })
                    ->when(count($orderNoArr), function ($query) use ($orderNoArr) {
                        $query->whereIn('map_township_plan_area.wgNumber', $orderNoArr);
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('map_township_plan_area.settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_township_plan_area.status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_township_plan_area.status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($openScore), function ($query) use ($openScore) {
                        $statusArr = explode(',', $openScore);
                        $query->whereBetween('map_township_plan_area.status', $statusArr);
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('map_township_plan_area.grade', $gradeArr);
                    })
                    ->when(mb_strlen($chosen), function ($query) use ($chosen) {
                        $chosenArr = explode(',', $chosen);
                        if (count($chosenArr) == 1) {
                            if ($chosen == 1) {
                                $query->where('map_township_plan_area.qianqiangTownRank', '!=', 0);
                            }
                            if ($chosen == 2) {
                                $query->where('map_township_plan_area.qianqiangTownRank', 0);
                            }
                        }
                    })
                    ->when(1, function ($query) use ($sort, $lng, $lat) {
                        switch ($sort) {
                            case ProgrammingEnum::TOWN_SORT_GRADE:
                                $query->orderBy("map_township_plan_area.grade", 'desc');
                                break;
                            case ProgrammingEnum::TOWN_SORT_NEAR:
                                $query->selectRaw("map_township_plan_area.*, ST_Distance_Sphere(POINT(`lng`, `lat`), POINT({$lng}, {$lat})) AS distance")->orderBy("distance");
                                break;
                            case ProgrammingEnum::TOWN_SORT_MAX_PEOPLE_COUNT:
                                $query->orderBy('map_township_plan_area.peopleCount', 'desc');
                                break;
                            case ProgrammingEnum::TOWN_SORT_PEOPLE_DENSITY:
                                $query->orderBy('map_township_plan_area.peopleDensityRank');
                                break;
                            default:
                                $query->orderBy("map_township_plan_area.grade", 'desc');
                        }
                    })
                    ->with(['logRel.resourceRelByCover', 'resourceWithMapRel', 'siteTaskRel'])
                    ->paginate($pageSize, ['map_township_plan_area.*'], 'page', $pageNum);

                $userInfos = [];
                if ($isKms) {
                    $assignIds = array_unique(array_column(array_column($paginator->items(), 'siteTaskRel'), 'assignId')) ?? [];//开发经理
                    $userInfos = KmsUser::getUserInfo($assignIds);                                                              //用户信息
                }
                $data      = [
                    'count'    => $paginator->total(),
                    'list'     => $history[] = array_map(function (MapTownshipPlanAreaModel $mapTownshipPlanAreaModel) use ($isKms, $userInfo, $userInfos) {
                        $cover = (string)optional($mapTownshipPlanAreaModel->resourceWithMapRel)->url ? picturePath($mapTownshipPlanAreaModel->resourceWithMapRel->url) : '';
                        if ($mapTownshipPlanAreaModel->logRel->count() != 0) {
                            foreach ($mapTownshipPlanAreaModel->logRel->toArray() as $log) {
                                foreach ($log['resource_rel_by_cover'] as $resource) {
                                    $type = json_decode($resource['extra'], true)['type'] ?? '-';
                                    if ($resource['name'] == ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION && $type == 'image') {
                                        $cover = picturePath($resource['url']);
                                    }
                                }
                            }
                        }
                        $distance = '';
                        if ($mapTownshipPlanAreaModel->distance) {
                            if (ceil($mapTownshipPlanAreaModel->distance) > 999) {
                                $distance = round(ceil($mapTownshipPlanAreaModel->distance) / 1000, 1) . 'km';
                            } else {
                                $distance = ceil($mapTownshipPlanAreaModel->distance) . 'm';
                            }
                        }

                        // 判断是否显示堪址按钮
                        $siteTaskButton = false;
                        if ((int)optional($mapTownshipPlanAreaModel->siteTaskRel)->assignId > 0 && (int)optional($mapTownshipPlanAreaModel->siteTaskRel)->assignId == ($userInfo['userId'] ?? 0)) {
                            $siteTaskButton = true;
                        }
                        $status     = $mapTownshipPlanAreaModel->status;
                        $statusText = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$mapTownshipPlanAreaModel->status] ?? '-';
                        $grade      = ProgrammingEnum::GRADE_MAPPING[$mapTownshipPlanAreaModel->grade] ?? '-';
                        if ($isKms) {
                            $projectPhase     = optional($mapTownshipPlanAreaModel->siteTaskRel)->projectPhase ?? 0;
                            $conversionStatus = self::conversionStatus($projectPhase);
                            $status           = $conversionStatus['status'];
                            $statusText       = $conversionStatus['statusText'];
                            $grade            = mb_substr($grade, 0, (mb_strlen($grade) - 1)) . '乡';
                        }

                        return [
                            'id'          => $mapTownshipPlanAreaModel->id,
                            'cover'       => $cover ?: 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                            'name'        => $mapTownshipPlanAreaModel->area,
                            'province'    => $mapTownshipPlanAreaModel->province,
                            'city'        => $mapTownshipPlanAreaModel->city,
                            'district'    => $mapTownshipPlanAreaModel->district,
                            'distance'    => $distance,
                            'area'        => $mapTownshipPlanAreaModel->area,
                            'address'     => $mapTownshipPlanAreaModel->address,
                            'status'      => $status,
                            'statusText'  => $statusText,
                            'grade'       => $grade,
                            'settleIn'    => $mapTownshipPlanAreaModel->settle ? '已入驻' : '',
                            'rank'        => array_merge(
                                ($mapTownshipPlanAreaModel->shopCountRank ? ['商超数排名第' . $mapTownshipPlanAreaModel->shopCountRank] : []),
                                ($mapTownshipPlanAreaModel->qianqiangTownRank ? ['千强镇第' . $mapTownshipPlanAreaModel->qianqiangTownRank . '名'] : [])
                            ),
                            'wgNumber'    => $mapTownshipPlanAreaModel->wgNumber,
                            'kfShopCount' => 0,
                            'type'        => ProgrammingEnum::PROGRAMMING_TOWN,
                            // 客户部堪址任务
                            'siteTaskButton'               => $siteTaskButton,
                            'siteTaskRelationId'           => (int)optional($mapTownshipPlanAreaModel->siteTaskRel)->id,
                            'siteTaskRelationAssignId'     => (int)optional($mapTownshipPlanAreaModel->siteTaskRel)->assignId,    //指派给
                            'siteTaskRelationUserName'     => $userInfos[optional($mapTownshipPlanAreaModel->siteTaskRel)->assignId ?? 0] ?? '',//用户名称
                            'siteTaskRelationAssignTime'   => optional($mapTownshipPlanAreaModel->siteTaskRel)->assignTime ?
                                date('Y-m-d', optional($mapTownshipPlanAreaModel->siteTaskRel)->assignTime) : '',  //指派时间
                            'siteTaskRelationFollowUpTime' => optional($mapTownshipPlanAreaModel->siteTaskRel)->followUpTime ?
                                date('Y-m-d', optional($mapTownshipPlanAreaModel->siteTaskRel)->followUpTime) : '',//最新跟进时间
                            'detail'      => [
                                [
                                    'name'  => '人口密度',
                                    'value' => round($mapTownshipPlanAreaModel->peopleDensity, 1),
                                ], [
                                    'name'  => '人口密度排名',
                                    'value' => $mapTownshipPlanAreaModel->peopleDensityRank,
                                ], [
                                    'name'  => '夸父门店数',
                                    'value' => $mapTownshipPlanAreaModel->shopNum,
                                ]
                            ]
                        ];
                    }, $paginator->items()),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                ];
                break;
            case ProgrammingEnum::PROGRAMMING_SCHOOL:  //学校网规
                $paginator = MapNationalUniversitiesModel::query()
                    ->when($isKms, function ($query) {
                        $query->leftJoin('customer_department_task', 'customer_department_task.wgNumber', '=', 'map_national_universities.wgNumber');
                    }
                    )
                    ->when(
                        ($isOwn || $statusArr) && $isKms, function ($query) use ($statusData, $statusArr, $isOwn, $userInfo) {
                        $query->when(
                            $isOwn, function ($query) use ($userInfo) {
                            $query->where('customer_department_task.assignId', $userInfo['userId'] ?? 0);//只看自己的
                        }
                        )->when(
                            $statusArr, function ($query) use ($statusData, $statusArr) {
                            $query->where(
                                function ($query) use ($statusData, $statusArr) {
                                    $query->when(
                                        $statusData, function ($query) use ($statusData) {
                                        $query->whereIn('customer_department_task.projectPhase', $statusData);//关联项目阶段状态
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && $statusData, function ($query) use ($statusArr) {
                                        $query->orWhere(
                                            function ($query) use ($statusArr) {
                                                $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                                ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                            }
                                        );
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && !$statusData, function ($query) use ($statusArr) {
                                        $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                        ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                    }
                                    );
                                }
                            );
                        }
                        );
                    }
                    )
                    ->when($searchId, function ($query) use ($searchId) {
                        $query->where('map_national_universities.id', $searchId);
                    })
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('map_national_universities.city', 'like', "%$city%");
                    })
                    ->when(mb_strlen($district), function ($query) use ($district) {
                        $query->where('map_national_universities.district', 'like', "%$district%");
                    })
                    ->when(
                        $provinceCodes, function ($query) use ($provinceCodes) {
                        $query->whereIn('map_national_universities.provinceCode', $provinceCodes);
                    }
                    )
                    ->when(
                        $cityCodes, function ($query) use ($cityCodes) {
                        $query->whereIn('map_national_universities.cityCode', $cityCodes);
                    }
                    )
                    ->when(
                        $districtCodes, function ($query) use ($districtCodes) {
                        $query->whereIn('map_national_universities.districtCode', $districtCodes);
                    }
                    )
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where(function ($q) use ($name) {
                            $q->where('map_national_universities.name', 'like', "%$name%")->orWhere('map_national_universities.address', 'like', "%$name%");
                        });
                    })
                    ->when(count($orderNoArr), function ($query) use ($orderNoArr) {
                        $query->whereIn('map_national_universities.wgNumber', $orderNoArr);
                    })
                    ->when(count($ids), function ($query) use ($ids) {
                        $query->whereIn('map_national_universities.id', $ids);
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('map_national_universities.settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_universities.status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_universities.status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($openScore), function ($query) use ($openScore) {
                        $statusArr = explode(',', $openScore);
                        $query->whereBetween('map_national_universities.status', $statusArr);
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('map_national_universities.grade', $gradeArr);
                    })
                    ->when(mb_strlen($chosen), function ($query) use ($chosen) {
                        $chosenArr = explode(',', $chosen);
                        if (in_array(1, $chosenArr)) {
                            $query->where('map_national_universities.project985', '是');
                        }
                        if (in_array(2, $chosenArr)) {
                            $query->where('map_national_universities.project211', '是');
                        }
                        if (in_array(3, $chosenArr)) {
                            $query->where('map_national_universities.strongBasis', '是');
                        }
                        if (in_array(4, $chosenArr)) {
                            $query->where('map_national_universities.doubleFirstClass', '是');
                        }
                    })
                    ->when(1, function ($query) use ($sort, $lng, $lat) {
                        switch ($sort) {
                            case ProgrammingEnum::SCHOOL_SORT_GRADE:
                                $query->orderBy("map_national_universities.grade", 'desc');
                                break;
                            case ProgrammingEnum::SCHOOL_SORT_NEAR:
                                $query->selectRaw("map_national_universities.*, ST_Distance_Sphere(POINT(`lon`, `lat`), POINT({$lng}, {$lat})) AS distance")->orderBy("distance");
                                break;
                            case ProgrammingEnum::SCHOOL_SORT_MAX_AREA:
                                $query->orderBy('map_national_universities.space', 'desc');
                                break;
                            default:
                                $query->orderBy("map_national_universities.grade", 'desc');
                        }
                    })
                    ->with(['logRel.resourceRelByCover', 'resourceWithMapRel', 'siteTaskRel'])
                    ->paginate($pageSize, ['map_national_universities.*'], 'page', $pageNum);

                $userInfos = [];
                if ($isKms) {
                    $assignIds = array_unique(array_column(array_column($paginator->items(), 'siteTaskRel'), 'assignId')) ?? [];//开发经理
                    $userInfos = KmsUser::getUserInfo($assignIds);                                                              //用户信息
                }
                $data      = [
                    'count'    => $paginator->total(),
                    'list'     => $history[] = array_map(function (MapNationalUniversitiesModel $mapNationalUniversitiesModel) use ($isKms, $userInfo, $userInfos) {
                        $cover = (string)optional($mapNationalUniversitiesModel->resourceWithMapRel)->url ? picturePath($mapNationalUniversitiesModel->resourceWithMapRel->url) : '';
                        if ($mapNationalUniversitiesModel->logRel->count() != 0) {
                            foreach ($mapNationalUniversitiesModel->logRel->toArray() as $log) {
                                foreach ($log['resource_rel_by_cover'] as $resource) {
                                    $type = json_decode($resource['extra'], true)['type'] ?? '-';
                                    if ($resource['name'] == ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION && $type == 'image') {
                                        $cover = picturePath($resource['url']);
                                    }
                                }
                            }
                        }
                        $distance = '';
                        if ($mapNationalUniversitiesModel->distance) {
                            if (ceil($mapNationalUniversitiesModel->distance) > 999) {
                                $distance = round(ceil($mapNationalUniversitiesModel->distance) / 1000, 1) . 'km';
                            } else {
                                $distance = ceil($mapNationalUniversitiesModel->distance) . 'm';
                            }
                        }

                        // 判断是否显示堪址按钮
                        $siteTaskButton = false;
                        if ((int)optional($mapNationalUniversitiesModel->siteTaskRel)->assignId > 0 && (int)optional($mapNationalUniversitiesModel->siteTaskRel)->assignId == ($userInfo['userId'] ?? 0)) {
                            $siteTaskButton = true;
                        }
                        $status     = $mapNationalUniversitiesModel->status;
                        $statusText = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$mapNationalUniversitiesModel->status] ?? '-';
                        $grade      = ProgrammingEnum::GRADE_MAPPING[$mapNationalUniversitiesModel->grade] ?? '-';
                        if ($isKms) {
                            $projectPhase     = optional($mapNationalUniversitiesModel->siteTaskRel)->projectPhase ?? 0;
                            $conversionStatus = self::conversionStatus($projectPhase);
                            $status           = $conversionStatus['status'];
                            $statusText       = $conversionStatus['statusText'];
                            $grade            = mb_substr($grade, 0, (mb_strlen($grade) - 1)) . '学';
                        }

                        return [
                            'id'         => $mapNationalUniversitiesModel->id,
                            'cover'      => $cover ?: 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                            'name'       => $mapNationalUniversitiesModel->name,
                            'province'   => $mapNationalUniversitiesModel->province,
                            'city'       => $mapNationalUniversitiesModel->city,
                            'district'   => $mapNationalUniversitiesModel->district,
                            'distance'   => $distance,
                            'area'       => '',
                            'address'    => $mapNationalUniversitiesModel->address,
                            'status'     => $status,
                            'statusText' => $statusText,
                            'grade'      => $grade,
                            'settleIn'   => $mapNationalUniversitiesModel->settle ? '已入驻' : '',
                            // 客户部堪址任务
                            'siteTaskButton'               => $siteTaskButton,
                            'siteTaskRelationId'           => (int)optional($mapNationalUniversitiesModel->siteTaskRel)->id,
                            'siteTaskRelationAssignId'     => (int)optional($mapNationalUniversitiesModel->siteTaskRel)->assignId,    //指派给
                            'siteTaskRelationUserName'     => $userInfos[optional($mapNationalUniversitiesModel->siteTaskRel)->assignId ?? 0] ?? '',//用户名称
                            'siteTaskRelationAssignTime'   => optional($mapNationalUniversitiesModel->siteTaskRel)->assignTime ?
                                date('Y-m-d', optional($mapNationalUniversitiesModel->siteTaskRel)->assignTime) : '',  //指派时间
                            'siteTaskRelationFollowUpTime' => optional($mapNationalUniversitiesModel->siteTaskRel)->followUpTime ?
                                date('Y-m-d', optional($mapNationalUniversitiesModel->siteTaskRel)->followUpTime) : '',//最新跟进时间
                            'rank'       => array_merge(
                                ($mapNationalUniversitiesModel->doubleFirstClass == '是' ? ['双一流'] : []),
                                ($mapNationalUniversitiesModel->project985 == '是' ? ['985'] : []),
                                ($mapNationalUniversitiesModel->project211 == '是' ? ['211'] : []),
                                ($mapNationalUniversitiesModel->strongBasis == '是' ? ['强基'] : [])
                            ),
                            'wgNumber'   => $mapNationalUniversitiesModel->wgNumber,
                            'type'       => ProgrammingEnum::PROGRAMMING_SCHOOL,
                            'detail'     => [
                                [
                                    'name'  => '院校类型',
                                    'value' => $mapNationalUniversitiesModel->schoolType,
                                ], [
                                    'name'  => '面积',
                                    'value' => $mapNationalUniversitiesModel->space . '亩',
                                ], [
                                    'name'  => '夸父门店数',
                                    'value' => $mapNationalUniversitiesModel->shopNum,
                                ]
                            ]
                        ];
                    }, $paginator->items()),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                ];
                break;
            case ProgrammingEnum::PROGRAMMING_INDUSTRIAL_PARKS:  //产业园区网规
                $paginator = MapNationalIndustrialParkModel::query()
                    ->when($isKms, function ($query) {
                        $query->leftJoin('customer_department_task', 'customer_department_task.wgNumber', '=', 'map_national_industrial_park.wgNumber');
                    }
                    )
                    ->when(
                        ($isOwn || $statusArr) && $isKms, function ($query) use ($statusData, $statusArr, $isOwn, $userInfo) {
                        $query->when(
                            $isOwn, function ($query) use ($userInfo) {
                            $query->where('customer_department_task.assignId', $userInfo['userId'] ?? 0);//只看自己的
                        }
                        )->when(
                            $statusArr, function ($query) use ($statusData, $statusArr) {
                            $query->where(
                                function ($query) use ($statusData, $statusArr) {
                                    $query->when(
                                        $statusData, function ($query) use ($statusData) {
                                        $query->whereIn('customer_department_task.projectPhase', $statusData);//关联项目阶段状态
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && $statusData, function ($query) use ($statusArr) {
                                        $query->orWhere(
                                            function ($query) use ($statusArr) {
                                                $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                                ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                            }
                                        );
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && !$statusData, function ($query) use ($statusArr) {
                                        $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                        ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                    }
                                    );
                                }
                            );
                        }
                        );
                    }
                    )
                    ->when($searchId, function ($query) use ($searchId) {
                        $query->where('map_national_industrial_park.id', $searchId);
                    })
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('map_national_industrial_park.city', 'like', "%$city%");
                    })
                    ->when(mb_strlen($district), function ($query) use ($district) {
                        $query->where('map_national_industrial_park.district', 'like', "%$district%");
                    })
                    ->when(
                        $provinceCodes, function ($query) use ($provinceCodes) {
                        $query->whereIn('map_national_industrial_park.provinceCode', $provinceCodes);
                    }
                    )
                    ->when(
                        $cityCodes, function ($query) use ($cityCodes) {
                        $query->whereIn('map_national_industrial_park.cityCode', $cityCodes);
                    }
                    )
                    ->when(
                        $districtCodes, function ($query) use ($districtCodes) {
                        $query->whereIn('map_national_industrial_park.districtCode', $districtCodes);
                    }
                    )
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('map_national_industrial_park.name', 'like', "%$name%");
                    })
                    ->when(count($ids), function ($query) use ($ids) {
                        $query->whereIn('map_national_industrial_park.id', $ids);
                    })
                    ->when(count($orderNoArr), function ($query) use ($orderNoArr) {
                        $query->whereIn('map_national_industrial_park.wgNumber', $orderNoArr);
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('map_national_industrial_park.settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_industrial_park.status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_industrial_park.status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($openScore), function ($query) use ($openScore) {
                        $statusArr = explode(',', $openScore);
                        $query->whereBetween('map_national_industrial_park.status', $statusArr);
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('map_national_industrial_park.grade', $gradeArr);
                    })
                    ->when(1, function ($query) use ($sort, $lng, $lat) {
                        switch ($sort) {
                            case ProgrammingEnum::SCHOOL_SORT_GRADE:
                                $query->orderBy("map_national_industrial_park.grade", 'desc');
                                break;
                            case ProgrammingEnum::SCHOOL_SORT_NEAR:
                                $query->selectRaw("map_national_industrial_park.*, ST_Distance_Sphere(POINT(`lon`, `lat`), POINT({$lng}, {$lat})) AS distance")->orderBy("distance");
                                break;
                            default:
                                $query->orderBy("map_national_industrial_park.grade", 'desc');
                        }
                    })
                    ->with(['logRel.resourceRelByCover', 'resourceWithMapRel', 'siteTaskRel'])
                    ->paginate($pageSize, ['map_national_industrial_park.*'], 'page', $pageNum);

                $userInfos = [];
                if ($isKms) {
                    $assignIds = array_unique(array_column(array_column($paginator->items(), 'siteTaskRel'), 'assignId')) ?? [];//开发经理
                    $userInfos = KmsUser::getUserInfo($assignIds);                                                              //用户信息
                }
                $data      = [
                    'count'    => $paginator->total(),
                    'list'     => $history[] = array_map(function (MapNationalIndustrialParkModel $mapNationalIndustrialParkModel) use ($isKms, $userInfo, $userInfos) {
                        $cover = (string)optional($mapNationalIndustrialParkModel->resourceWithMapRel)->url ? picturePath($mapNationalIndustrialParkModel->resourceWithMapRel->url) : '';
                        if ($mapNationalIndustrialParkModel->logRel->count() != 0) {
                            foreach ($mapNationalIndustrialParkModel->logRel->toArray() as $log) {
                                foreach ($log['resource_rel_by_cover'] as $resource) {
                                    $type = json_decode($resource['extra'], true)['type'] ?? '-';
                                    if ($resource['name'] == ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION && $type == 'image') {
                                        $cover = picturePath($resource['url']);
                                    }
                                }
                            }
                        }
                        $distance = '';
                        if ($mapNationalIndustrialParkModel->distance) {
                            if (ceil($mapNationalIndustrialParkModel->distance) > 999) {
                                $distance = round(ceil($mapNationalIndustrialParkModel->distance) / 1000, 1) . 'km';
                            } else {
                                $distance = ceil($mapNationalIndustrialParkModel->distance) . 'm';
                            }
                        }

                        // 判断是否显示堪址按钮
                        $siteTaskButton = false;
                        if ((int)optional($mapNationalIndustrialParkModel->siteTaskRel)->assignId > 0 && (int)optional($mapNationalIndustrialParkModel->siteTaskRel)->assignId == ($userInfo['userId'] ?? 0)) {
                            $siteTaskButton = true;
                        }
                        $status     = $mapNationalIndustrialParkModel->status;
                        $statusText = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$mapNationalIndustrialParkModel->status] ?? '-';
                        $grade      = ProgrammingEnum::GRADE_MAPPING[$mapNationalIndustrialParkModel->grade] ?? '-';
                        if ($isKms) {
                            $projectPhase     = optional($mapNationalIndustrialParkModel->siteTaskRel)->projectPhase ?? 0;
                            $conversionStatus = self::conversionStatus($projectPhase);
                            $status           = $conversionStatus['status'];
                            $statusText       = $conversionStatus['statusText'];
                            $grade            = mb_substr($grade, 0, (mb_strlen($grade) - 1)) . '园';
                        }

                        return [
                            'id'         => $mapNationalIndustrialParkModel->id,
                            'cover'      => $cover ?: 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                            'name'       => $mapNationalIndustrialParkModel->name,
                            'province'   => $mapNationalIndustrialParkModel->province,
                            'city'       => $mapNationalIndustrialParkModel->city,
                            'district'   => $mapNationalIndustrialParkModel->district,
                            'distance'   => $distance,
                            'settleIn'   => $mapNationalIndustrialParkModel->settle ? '已入驻' : '',
                            'rank'       => [],
                            'status'     => $status,
                            'grade'      => $grade,
                            'statusText' => $statusText,
                            'wgNumber'   => $mapNationalIndustrialParkModel->wgNumber,
                            'type'       => ProgrammingEnum::PROGRAMMING_INDUSTRIAL_PARKS,
                            // 客户部堪址任务
                            'siteTaskButton'               => $siteTaskButton,
                            'siteTaskRelationId'           => (int)optional($mapNationalIndustrialParkModel->siteTaskRel)->id,
                            'siteTaskRelationAssignId'     => (int)optional($mapNationalIndustrialParkModel->siteTaskRel)->assignId,    //指派给
                            'siteTaskRelationUserName'     => $userInfos[optional($mapNationalIndustrialParkModel->siteTaskRel)->assignId ?? 0] ?? '',//用户名称
                            'siteTaskRelationAssignTime'   => optional($mapNationalIndustrialParkModel->siteTaskRel)->assignTime ?
                                date('Y-m-d', optional($mapNationalIndustrialParkModel->siteTaskRel)->assignTime) : '',  //指派时间
                            'siteTaskRelationFollowUpTime' => optional($mapNationalIndustrialParkModel->siteTaskRel)->followUpTime ?
                                date('Y-m-d', optional($mapNationalIndustrialParkModel->siteTaskRel)->followUpTime) : '',//最新跟进时间
                            'detail'     => [
                                [
                                    'name'  => '夸父门店数',
                                    'value' => $mapNationalIndustrialParkModel->shopNum,
                                ]
                            ],
                        ];
                    }, $paginator->items()),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                ];
                break;
            default:
                if (!in_array($subType, [ProgrammingEnum::SUB_TYPE_BROWSING, ProgrammingEnum::SUB_TYPE_AUDIT])) {
                    self::throwErr('网规类型不存在,请联系相关负责人');
                }
                if ($subType == ProgrammingEnum::SUB_TYPE_BROWSING) {
                    $data = self::browsingHistory($userInfo['userId'], 1, 999999, $name);
                }

                if ($subType == ProgrammingEnum::SUB_TYPE_AUDIT) {
                    $data = self::evaluateHistory($userInfo['userId'], 1, 999999, $name);
                }
        }
        if (count($ids) || count($orderNoArr)) {
            return $history;
        }
        return $data;
    }


    /**
     * @throws GuzzleException
     * @throws \Exception
     */
    public static function detail($type, $id, $rmsUserId)
    {
        $data = [];
        switch ($type) {
            case ProgrammingEnum::PROGRAMMING_MALL:  //商场网规
                $siteLocationMallModel = SiteLocationMallModel::query()
                    ->where('grade', '>', 0)
                    ->with(['resourceWithMapRel', 'siteTaskRel'])
                    ->find($id);
                if (null == $siteLocationMallModel) {
                    self::throwErr('获取详情失败');
                }
                $orderNo               = $siteLocationMallModel->wgNumber;
                $name                  = $siteLocationMallModel->mallName;

                // 判断是否显示堪址按钮
                $siteTaskButton = false;
                if ((int)optional($siteLocationMallModel->siteTaskRel)->assignId > 0 && (int)optional($siteLocationMallModel->siteTaskRel)->assignId == $rmsUserId) {
                    $siteTaskButton = true;
                }

                $data                  = [
                    'id'         => $siteLocationMallModel->id,
                    'mallId'     => $siteLocationMallModel->mallId,
                    'isMall'     => true,
                    'cover'      => (string)optional($siteLocationMallModel->resourceWithMapRel)->url ? picturePath($siteLocationMallModel->resourceWithMapRel->url) : 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                    'name'       => $siteLocationMallModel->mallName,
                    'province'   => $siteLocationMallModel->province,
                    'city'       => $siteLocationMallModel->city,
                    'district'   => $siteLocationMallModel->district,
                    'recommendFloor'   => $siteLocationMallModel->recommendFloor, //推荐楼层
                    'area'       => $siteLocationMallModel->area,
                    'address'    => $siteLocationMallModel->address,
                    'status'     => $siteLocationMallModel->status,
                    'statusText' => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$siteLocationMallModel->status] ?? '-',
                    'grade'      => OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_SIFT_MAPPING[$siteLocationMallModel->grade] ?? '-',
                    'lat'        => $siteLocationMallModel->lat,
                    'lng'        => $siteLocationMallModel->lng,
                    'info'       => [
                        'phone'             => explode('|', $siteLocationMallModel->phone),
                        'shopTotalCount'    => $siteLocationMallModel->shopTotalCount,
                        'foodRatio'         => $siteLocationMallModel->foodRatio,
                        'topList'           => $siteLocationMallModel->topList,
                        'mallStatus'        => $siteLocationMallModel->mallStatus,
                        'mallStatusText'    => SiteLocationMallModel::MALL_BUSINESS_STATUS_MAPPING[$siteLocationMallModel->mallStatus] ?? '-',
                        'facilitiesRating'  => $siteLocationMallModel->facilitiesRating,
                        'environmentRating' => $siteLocationMallModel->environmentRating,
                        'serviceRating'     => $siteLocationMallModel->serviceRating,
                    ],
                    'wgNumber'   => $orderNo,
                    'settleIn'   => $siteLocationMallModel->settle ? '已入驻' : '',
                    'rank'       => array_merge(
                        (mb_strlen($siteLocationMallModel->topList) ? [$siteLocationMallModel->topList] : [])
                    ),
                    'type'       => ProgrammingEnum::PROGRAMMING_MALL,
                    // 客户部堪址任务
                    'siteTaskButton'     => $siteTaskButton,
                    'siteTaskRelationId' => (int)optional($siteLocationMallModel->siteTaskRel)->id,
                    'detail'     => [
                        [
                            'name'  => '店铺总数',
                            'value' => $siteLocationMallModel->shopTotalCount,
                        ], [
                            'name'  => '美食店铺占比',
                            'value' => $siteLocationMallModel->foodRatio ? ($siteLocationMallModel->foodRatio * 100 . '%') : 0,
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $siteLocationMallModel->shopNum,
                        ]
                    ]
                ];
                break;
            case ProgrammingEnum::PROGRAMMING_STREET:  //街道网规
                $mapNationalStreetModel = MapNationalStreetModel::query()->with(['resourceWithMapRel', 'siteTaskRel'])->find($id);
                $orderNo                = $mapNationalStreetModel->wgNumber;
                if (mb_strpos($mapNationalStreetModel->address, $mapNationalStreetModel->name) === false) {
                    $name = $mapNationalStreetModel->name;
                } else {
                    $name = mb_substr($mapNationalStreetModel->address, mb_strpos($mapNationalStreetModel->address, $mapNationalStreetModel->name));
                }

                // 判断是否显示堪址按钮
                $siteTaskButton = false;
                if ((int)optional($mapNationalStreetModel->siteTaskRel)->assignId > 0 && (int)optional($mapNationalStreetModel->siteTaskRel)->assignId == $rmsUserId) {
                    $siteTaskButton = true;
                }

                $data = [
                    'id'         => $mapNationalStreetModel->id,
                    'cover'      => (string)optional($mapNationalStreetModel->resourceWithMapRel)->url ? picturePath($mapNationalStreetModel->resourceWithMapRel->url) : 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                    'name'       => $name,
                    'province'   => $mapNationalStreetModel->province,
                    'city'       => $mapNationalStreetModel->city,
                    'district'   => $mapNationalStreetModel->district,
                    'area'       => '',
                    'address'    => $mapNationalStreetModel->address,
                    'status'     => $mapNationalStreetModel->status,
                    'statusText' => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$mapNationalStreetModel->status] ?? '-',
                    'grade'      => ProgrammingEnum::GRADE_MAPPING[$mapNationalStreetModel->grade] ?? '-',
                    'lat'        => $mapNationalStreetModel->lat,
                    'lng'        => $mapNationalStreetModel->lng,
                    'coords'     => $mapNationalStreetModel->coordsArr,
                    'info'       => [],
                    'wgNumber'   => $orderNo,
                    'type'       => ProgrammingEnum::PROGRAMMING_STREET,
                    // 客户部堪址任务
                    'siteTaskButton'     => $siteTaskButton,
                    'siteTaskRelationId' => (int)optional($mapNationalStreetModel->siteTaskRel)->id,
                    'detail'     => [
                        [
                            'name'  => '夸父门店数',
                            'value' => $mapNationalStreetModel->shopNum,
                        ]
                    ],
                    'rank'       => [],
                    'settleIn'   => $mapNationalStreetModel->settle ? '已入驻' : '',
                ];
                break;
            case ProgrammingEnum::PROGRAMMING_COMMUNITY:  //街道网规
                $mapNationalCommunityModel = MapNationalCommunityModel::query()->with(['resourceWithMapRel', 'siteTaskRel'])->find($id);
                $orderNo                = $mapNationalCommunityModel->wgNumber;
                if (mb_strpos($mapNationalCommunityModel->address, $mapNationalCommunityModel->name) === false) {
                    $name = $mapNationalCommunityModel->name;
                } else {
                    $name = mb_substr($mapNationalCommunityModel->address, mb_strpos($mapNationalCommunityModel->address, $mapNationalCommunityModel->name));
                }

                // 判断是否显示堪址按钮
                $siteTaskButton = false;
                if ((int)optional($mapNationalCommunityModel->siteTaskRel)->assignId > 0 && (int)optional($mapNationalCommunityModel->siteTaskRel)->assignId == $rmsUserId) {
                    $siteTaskButton = true;
                }

                $data = [
                    'id'         => $mapNationalCommunityModel->id,
                    'cover'      => (string)optional($mapNationalCommunityModel->resourceWithMapRel)->url ? picturePath($mapNationalCommunityModel->resourceWithMapRel->url) : 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                    'name'       => $name,
                    'province'   => $mapNationalCommunityModel->province,
                    'city'       => $mapNationalCommunityModel->city,
                    'district'   => $mapNationalCommunityModel->district,
                    'area'       => '',
                    'address'    => $mapNationalCommunityModel->address,
                    'status'     => $mapNationalCommunityModel->status,
                    'statusText' => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$mapNationalCommunityModel->status] ?? '-',
                    'grade'      => ProgrammingEnum::GRADE_MAPPING[$mapNationalCommunityModel->grade] ?? '-',
                    'lat'        => $mapNationalCommunityModel->lat,
                    'lng'        => $mapNationalCommunityModel->lng,
                    'coords'     => $mapNationalCommunityModel->coordsArr,
                    'info'       => [],
                    'wgNumber'   => $orderNo,
                    'type'       => ProgrammingEnum::PROGRAMMING_STREET,
                    // 客户部堪址任务
                    'siteTaskButton'     => $siteTaskButton,
                    'siteTaskRelationId' => (int)optional($mapNationalCommunityModel->siteTaskRel)->id,
                    'detail'     => [
                        [
                            'name'  => '夸父门店数',
                            'value' => $mapNationalCommunityModel->shopNum,
                        ]
                    ],
                    'rank'       => [],
                    'settleIn'   => $mapNationalCommunityModel->settle ? '已入驻' : '',
                ];
                break;
            case ProgrammingEnum::PROGRAMMING_TOWN:  //乡镇网规
                $mapTownshipPlanAreaModel = MapTownshipPlanAreaModel::query()->with(['resourceWithMapRel', 'siteTaskRel'])->find($id);
                $orderNo                  = $mapTownshipPlanAreaModel->wgNumber;
                $name                     = $mapTownshipPlanAreaModel->area;

                // 判断是否显示堪址按钮
                $siteTaskButton = false;
                if ((int)optional($mapTownshipPlanAreaModel->siteTaskRel)->assignId > 0 && (int)optional($mapTownshipPlanAreaModel->siteTaskRel)->assignId == $rmsUserId) {
                    $siteTaskButton = true;
                }

                $data                     = [
                    'id'         => $mapTownshipPlanAreaModel->id,
                    'cover'      => (string)optional($mapTownshipPlanAreaModel->resourceWithMapRel)->url ? picturePath($mapTownshipPlanAreaModel->resourceWithMapRel->url) : 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                    'name'       => $mapTownshipPlanAreaModel->area,
                    'province'   => $mapTownshipPlanAreaModel->province,
                    'city'       => $mapTownshipPlanAreaModel->city,
                    'district'   => $mapTownshipPlanAreaModel->district,
                    'area'       => $mapTownshipPlanAreaModel->area,
                    'address'    => $mapTownshipPlanAreaModel->address,
                    'status'     => $mapTownshipPlanAreaModel->status,
                    'statusText' => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$mapTownshipPlanAreaModel->status] ?? '-',
                    'grade'      => ProgrammingEnum::GRADE_MAPPING[$mapTownshipPlanAreaModel->grade] ?? '-',
                    'lat'        => $mapTownshipPlanAreaModel->lat,
                    'lng'        => $mapTownshipPlanAreaModel->lng,
                    'info'       => [
                        'shopCountRank'     => $mapTownshipPlanAreaModel->shopCountRank,
                        'qianqiangTownRank' => $mapTownshipPlanAreaModel->qianqiangTownRank,
                        'totalRank'         => $mapTownshipPlanAreaModel->totalRank,
                        'peopleDensity'     => $mapTownshipPlanAreaModel->peopleDensity,
                        'peopleDensityRank' => $mapTownshipPlanAreaModel->peopleDensityRank,
                        'peopleCount'       => $mapTownshipPlanAreaModel->peopleCount,
                        'shopNum'           => $mapTownshipPlanAreaModel->shopNum,
                    ],
                    'wgNumber'   => $orderNo,
                    'type'       => ProgrammingEnum::PROGRAMMING_TOWN,
                    // 客户部堪址任务
                    'siteTaskButton'     => $siteTaskButton,
                    'siteTaskRelationId' => (int)optional($mapTownshipPlanAreaModel->siteTaskRel)->id,
                    'detail'     => [
                        [
                            'name'  => '人口密度',
                            'value' => round($mapTownshipPlanAreaModel->peopleDensity, 1),
                        ], [
                            'name'  => '人口密度排名',
                            'value' => $mapTownshipPlanAreaModel->peopleDensityRank,
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $mapTownshipPlanAreaModel->shopNum,
                        ]
                    ],
                    'settleIn'   => $mapTownshipPlanAreaModel->settle ? '已入驻' : '',
                    'rank'       => array_merge(
                        ($mapTownshipPlanAreaModel->shopCountRank ? ['商超数排名第' . $mapTownshipPlanAreaModel->shopCountRank] : []),
                        ($mapTownshipPlanAreaModel->qianqiangTownRank ? ['千强镇第' . $mapTownshipPlanAreaModel->qianqiangTownRank . '名'] : [])
                    ),
                ];
                break;
            case ProgrammingEnum::PROGRAMMING_SCHOOL:  //学校网规
                $mapNationalUniversitiesModel = MapNationalUniversitiesModel::query()->with(['resourceWithMapRel', 'siteTaskRel'])->find($id);
                $orderNo                      = $mapNationalUniversitiesModel->wgNumber;
                $name                         = $mapNationalUniversitiesModel->name;

                // 判断是否显示堪址按钮
                $siteTaskButton = false;
                if ((int)optional($mapNationalUniversitiesModel->siteTaskRel)->assignId > 0 && (int)optional($mapNationalUniversitiesModel->siteTaskRel)->assignId == $rmsUserId) {
                    $siteTaskButton = true;
                }

                $data                         = [
                    'id'         => $mapNationalUniversitiesModel->id,
                    'cover'      => (string)optional($mapNationalUniversitiesModel->resourceWithMapRel)->url ? picturePath($mapNationalUniversitiesModel->resourceWithMapRel->url) : 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                    'name'       => $mapNationalUniversitiesModel->name,
                    'province'   => $mapNationalUniversitiesModel->province,
                    'city'       => $mapNationalUniversitiesModel->city,
                    'district'   => $mapNationalUniversitiesModel->district,
                    'area'       => '',
                    'address'    => $mapNationalUniversitiesModel->address,
                    'status'     => $mapNationalUniversitiesModel->status,
                    'statusText' => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$mapNationalUniversitiesModel->status] ?? '-',
                    'grade'      => ProgrammingEnum::GRADE_MAPPING[$mapNationalUniversitiesModel->grade] ?? '-',
                    'lat'        => $mapNationalUniversitiesModel->lat,
                    'lng'        => $mapNationalUniversitiesModel->lon,
                    'info'       => [
                        'attachedTo'       => $mapNationalUniversitiesModel->attachedTo,
                        'project985'       => $mapNationalUniversitiesModel->project985 == '是',
                        'project211'       => $mapNationalUniversitiesModel->project211 == '是',
                        'doubleFirstClass' => $mapNationalUniversitiesModel->doubleFirstClass == '是',
                        'space'            => $mapNationalUniversitiesModel->space,
                        'schoolType'       => $mapNationalUniversitiesModel->schoolType,
                        'educationType'    => $mapNationalUniversitiesModel->educationType,
                        'educationNature'  => $mapNationalUniversitiesModel->educationNature,
                        'phone'            => explode(',', $mapNationalUniversitiesModel->tel),
                    ],
                    'wgNumber'   => $orderNo,
                    'settleIn'   => $mapNationalUniversitiesModel->settle ? '已入驻' : '',
                    'rank'       => array_merge(
                        ($mapNationalUniversitiesModel->doubleFirstClass == '是' ? ['双一流'] : []),
                        ($mapNationalUniversitiesModel->project985 == '是' ? ['985'] : []),
                        ($mapNationalUniversitiesModel->project211 == '是' ? ['211'] : []),
                        ($mapNationalUniversitiesModel->strongBasis == '是' ? ['强基'] : [])
                    ),
                    'type'       => ProgrammingEnum::PROGRAMMING_SCHOOL,
                    // 客户部堪址任务
                    'siteTaskButton'     => $siteTaskButton,
                    'siteTaskRelationId' => (int)optional($mapNationalUniversitiesModel->siteTaskRel)->id,
                    'detail'     => [
                        [
                            'name'  => '院校类型',
                            'value' => $mapNationalUniversitiesModel->schoolType,
                        ], [
                            'name'  => '面积',
                            'value' => $mapNationalUniversitiesModel->space . '亩',
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $mapNationalUniversitiesModel->shopNum,
                        ]
                    ]
                ];
                break;
            case ProgrammingEnum::PROGRAMMING_INDUSTRIAL_PARKS:  //产业园区网规
                $mapNationalIndustrialParkModel = MapNationalIndustrialParkModel::query()->with(['resourceWithMapRel', 'siteTaskRel'])->find($id);
                $orderNo                        = $mapNationalIndustrialParkModel->wgNumber;
                $name                           = $mapNationalIndustrialParkModel->name;

                // 判断是否显示堪址按钮
                $siteTaskButton = false;
                if ((int)optional($mapNationalIndustrialParkModel->siteTaskRel)->assignId > 0 && (int)optional($mapNationalIndustrialParkModel->siteTaskRel)->assignId == $rmsUserId) {
                    $siteTaskButton = true;
                }

                $data                           = [
                    'id'         => $mapNationalIndustrialParkModel->id,
                    'cover'      => (string)optional($mapNationalIndustrialParkModel->resourceWithMapRel)->url ? picturePath($mapNationalIndustrialParkModel->resourceWithMapRel->url) : 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                    'name'       => $mapNationalIndustrialParkModel->name,
                    'province'   => $mapNationalIndustrialParkModel->province,
                    'city'       => $mapNationalIndustrialParkModel->city,
                    'district'   => $mapNationalIndustrialParkModel->district,
                    'area'       => '',
                    'address'    => '',
                    'status'     => $mapNationalIndustrialParkModel->status,
                    'statusText' => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$mapNationalIndustrialParkModel->status] ?? '-',
                    'grade'      => ProgrammingEnum::GRADE_MAPPING[$mapNationalIndustrialParkModel->grade] ?? '-',
                    'lat'        => $mapNationalIndustrialParkModel->lat,
                    'lng'        => $mapNationalIndustrialParkModel->lon,
                    'info'       => [],
                    'wgNumber'   => $mapNationalIndustrialParkModel->wgNumber,
                    'type'       => ProgrammingEnum::PROGRAMMING_INDUSTRIAL_PARKS,
                    // 客户部堪址任务
                    'siteTaskButton'     => $siteTaskButton,
                    'siteTaskRelationId' => (int)optional($mapNationalIndustrialParkModel->siteTaskRel)->id,
                    'detail'     => [
                        [
                            'name'  => '夸父门店数',
                            'value' => $mapNationalIndustrialParkModel->shopNum,
                        ]
                    ],
                    'settleIn'   => $mapNationalIndustrialParkModel->settle ? '已入驻' : '',
                    'rank'       => [],
                ];
                break;
            default:
                self::throwErr('网规类型错误');
        }

        //添加浏览记录
        $browsing            = WangguiBrowsingHistoryModel::query()
            ->updateOrCreate([
                'createdByUid' => $rmsUserId,
                'updatedByUid' => $rmsUserId,
                'type'         => $type,
                'wgNumber'     => $orderNo,
                'businessId'   => $id,
            ]);
        $browsing->updatedAt = time();
        $browsing->wgName    = $name;
        $browsing->save();

        $logModel           = OpenShopSiteLocationExamineLogModel::query()
            ->where('source', OpenShopSiteLocationExamineLogModel::SOURCE_WG_AUDIT)
            ->orderBy('updatedAt', 'desc')
            ->where('orderNo', $orderNo)
            ->with(['resourceRelUsedToShow', 'wangguiSiteDistrictRel.resourceRel'])
            ->get();
        $body               = RmsUserService::getRmsUserInfoByUserIds($logModel->pluck('createdByUid')->toArray())['data'] ?? [];
        $userNames          = array_column($body, 'username', 'id');
        $auditEffectiveTime = ConfigService::config('wanggui', 'auditEffectiveTime')['auditEffectiveTime'] ?? 0;
        $log                = $logModel->map(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use ($userNames, $rmsUserId, $auditEffectiveTime) {
            $file = [];
            $locationExamineLogModel->resourceRelUsedToShow->each(function (ResourcesModel $resourcesModel) use (&$file) {
                $file[$resourcesModel->name][] = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
            });
            return array_merge([
                'id'                 => $locationExamineLogModel->id,
                'username'           => $userNames[$locationExamineLogModel->createdByUid] ?? '-',
                'status'             => $locationExamineLogModel->status,
                'openPotential'      => $locationExamineLogModel->openPotential,
                'flowOfPeopleScores' => $locationExamineLogModel->flowOfPeopleScores,
                'statusText'         => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-',
                'createdAt'          => $locationExamineLogModel->updatedAt->format('Y-m-d H:i'),
                'evaluateTime'       => $locationExamineLogModel->updatedAt->format('Y-m-d H:i'),
                'content'            => $locationExamineLogModel->content,
                'isUpdate'           => $locationExamineLogModel->createdByUid == $rmsUserId && time() < ($locationExamineLogModel->updatedAt->timestamp + $auditEffectiveTime * 3600),
                'weather'            => DateTool::cnWeekOfDay($locationExamineLogModel->updatedAt->dayOfWeek) . ' ' . (json_decode($locationExamineLogModel->extra, true)['weather'] ?? ''),
                'openDistrictList'   => $locationExamineLogModel->wangguiSiteDistrictRel->map(function (WangguiSiteDistrictModel $wangguiSiteDistrictModel) {
                    return [
                        'id'              => $wangguiSiteDistrictModel->id,
                        'name'            => $wangguiSiteDistrictModel->name,
                        'isEmptyShop'     => $wangguiSiteDistrictModel->isEmptyShop,
                        'isEmptyShopText' => WangguiSiteDistrictModel::IS_EMPTY_SHOP_MAPPING[$wangguiSiteDistrictModel->isEmptyShop] ?? '',
                        'file'            => $wangguiSiteDistrictModel->resourceRel->map(function (ResourcesModel $resourcesModel) {
                            return [
                                'url'  => picturePath($resourcesModel->url),
                                'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')
                            ];
                        })
                    ];
                })
            ], $file);
        })->values();

        //获得外卖预估
        $distance = 3;  //默认3km
        // 外卖预估数据
        $takeOutData = (new WaiMaiAnalysisService())
            ->setLngLat($data['lng'], $data['lat'], $distance);
        $estimate    = $takeOutData->calcEstimateData();
        $takeOutInfo = [
            'takeOutDoubleSalesVolume'         => (int)(array_sum($estimate['estimate']) * 0.8) . '~' . (int)(array_sum($estimate['estimate']) * 1.2),
            'takeOutDoubleSalesVolumeReceived' => ((int)(array_sum($estimate['estimate']) * 0.8) * 30) . '~' . ((int)(array_sum($estimate['estimate']) * 1.2) * 30),
            'mtSalesVolume'                    => (int)($estimate['estimate']['mt'] * 0.8) . '~' . (int)($estimate['estimate']['mt'] * 1.2),
            'elmSalesVolume'                   => (int)($estimate['estimate']['elm'] * 0.8) . '~' . (int)($estimate['estimate']['elm'] * 1.2),
        ];

        $data['takeOutInfo'] = $takeOutInfo;
        //        $file = [
        //            'image' => [],
        //            'video' => [],
        //        ];
        //        ResourcesModel::query()
        //            ->where('businessId', $id)
        //            ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
        //            ->where('business', $business)
        //            ->get()
        //            ->each(function (ResourcesModel $resources) use (&$file) {
        //                $file[$resources->name][] = picturePath($resources->url);
        //            });
        //        $data['file'] = $file;
        $data['log'] = $log;
        return $data;
    }


    public static function getNearbyDot($lng, $lat)
    {
        //获得该点位3km内的点位信息
        $dotList  = Redis::georadius('tiger:wanggui:dot', $lng, $lat, '3000', 'm', ['WITHDIST', 'ASC']);
        $kf       = [];
        $kfDot    = [];
        $kfList   = [];
        $sc       = [];
        $scDot    = [];
        $scList   = [];
        $cyy      = [];
        $cyyDot   = [];
        $cyyList  = [];
        $xq       = [];
        $xqDot    = [];
        $xqList   = [];
        $brand    = [];
        $brandDot = [];
        foreach ($dotList as $dot) {
            $type = substr($dot[0], 0, 2);
            switch ($type) {
                case 'SC':  //商城
                    $sc[]           = $dot[0];
                    $scDot[$dot[0]] = $dot[1];
                    break;
                case 'CY':  //产业园
                    $cyy[]           = $dot[0];
                    $cyyDot[$dot[0]] = $dot[1];
                    break;
                case 'XQ':  //小区
                    $xq[]                      = substr($dot[0], 4);
                    $xqDot[substr($dot[0], 4)] = $dot[1];
                    break;
                case 'PP':  // 品牌
                    $brand[]           = $dot[0];
                    $brandDot[$dot[0]] = $dot[1];
                    break;
                case 'KF':  // 夸父
                    $kf[]             = $dot[0];
                    $shopCode         = (string)substr($dot[0], -4);
                    $kfDot[$shopCode] = $dot[1];
                    break;
                default:
            }
        }
        if (count($kf)) {
            try {
                $kfShop  = GuanyuanDataService::newShopList();
            } catch (\Exception $exception) {
                $kfShop = [];
            }

            // 调整夸父门店编号
            $kf = collect($kf)->map(function ($item) {
                return (string)substr($item, -4);
            })->toArray();

            collect($kfShop)->each(function ($shop) use (&$kfList, $kfDot, $kf) {
                $shopCode = str_pad($shop['铺位号'], 4, "0", STR_PAD_LEFT);
                if (in_array($shopCode, $kf)) {
                    $kfList[] = [
                        'distance' => (int)ceil($kfDot[$shopCode] ?? 0),
                        'name'     => $shop['门店名称'],
                        'address'  => $shop['店铺地址'],
                        'lng'      => $shop['门店经度'],
                        'status'   => $shop['状态'],
                        'lat'      => $shop['门店纬度'],
                        'grade'    => '',
                    ];
                }
            });
            $kfList = collect($kfList)->sortBy('distance')->values();
        }
        if (count($sc)) {
            $scList = SiteLocationMallModel::query()
                ->where('grade', '>', 0)
                ->whereIn('wgNumber', $sc)
                ->get()
                ->map(function (SiteLocationMallModel $siteLocationMallModel) use ($scDot) {
                    return [
                        'distance'   => ceil($scDot[$siteLocationMallModel->wgNumber] ?? 0),
                        'name'       => $siteLocationMallModel->mallName,
                        'status'     => $siteLocationMallModel->status,
                        'address'    => $siteLocationMallModel->address,
                        'statusText' => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$siteLocationMallModel->status] ?? '-',
                        'grade'      => OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_SIFT_MAPPING[$siteLocationMallModel->grade] ?? '-',
                        'lng'        => $siteLocationMallModel->lng,
                        'lat'        => $siteLocationMallModel->lat,
                    ];
                })->sortBy('distance')->values();
        }
        if (count($cyy)) {
            $cyyList = MapNationalIndustrialParkModel::query()
                ->whereIn('wgNumber', $cyy)
                ->get()
                ->map(function (MapNationalIndustrialParkModel $mapNationalIndustrialParkModel) use ($cyyDot) {
                    return [
                        'distance'   => ceil($cyyDot[$mapNationalIndustrialParkModel->wgNumber] ?? 0),
                        'lng'        => $mapNationalIndustrialParkModel->lon,
                        'lat'        => $mapNationalIndustrialParkModel->lat,
                        'name'       => $mapNationalIndustrialParkModel->name,
                        'address'    => $mapNationalIndustrialParkModel->province . '-' . $mapNationalIndustrialParkModel->city . '-' . $mapNationalIndustrialParkModel->district,
                        'status'     => $mapNationalIndustrialParkModel->status,
                        'statusText' => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$mapNationalIndustrialParkModel->status] ?? '-',
                        'grade'      => ProgrammingEnum::GRADE_MAPPING[$mapNationalIndustrialParkModel->grade] ?? '-',
                    ];
                })->sortBy('distance')->values();
        }
        if (count($xq)) {
            $xqList = CityResidencePriceModel::query()
                ->whereIn('id', $xq)
                ->get()
                ->map(function (CityResidencePriceModel $cityResidencePriceModel) use ($xqDot) {
                    return [
                        'distance' => ceil($xqDot[str_pad($cityResidencePriceModel->id, 7, '0', STR_PAD_LEFT)] ?? 0),
                        'lng'      => $cityResidencePriceModel->centerLongitude,
                        'lat'      => $cityResidencePriceModel->centerLatitude,
                        'name'     => $cityResidencePriceModel->name,
                        'address'  => $cityResidencePriceModel->province . '-' . $cityResidencePriceModel->city . '-' . $cityResidencePriceModel->district,
                        'grade'    => '',
                    ];
                })->sortBy('distance')->values();
        }
        $brandData = [];
        MapNationalBrandShopModel::query()
            ->whereIn('wgNumber', $brand)
            ->get()
            ->each(function (MapNationalBrandShopModel $mapNationalBrandShopModel) use (&$brandData, $brandDot) {
                $name = $mapNationalBrandShopModel->name;
                if (mb_strpos($mapNationalBrandShopModel->name, $mapNationalBrandShopModel->brand) === false) {
                    $name = $mapNationalBrandShopModel->brand . '·' . $mapNationalBrandShopModel->name;
                }
                $brandData[ProgrammingEnum::BRAND_SHOP_MAPPING[$mapNationalBrandShopModel->brand]][] = [
                    'distance' => ceil($brandDot[$mapNationalBrandShopModel->wgNumber] ?? 0),
                    'lng'      => $mapNationalBrandShopModel->lon,
                    'lat'      => $mapNationalBrandShopModel->lat,
                    'name'     => $name,
                    'address'  => $mapNationalBrandShopModel->address,
                    'grade'    => '',
                ];
            });

        foreach ($brandData as $key => $brandDatum) {
            $brandData[$key] = collect($brandDatum)->sortBy('distance')->values();
        }

        return array_merge([
            'kuafu'                      => $kfList,
            'mallData'                   => $scList,
            'residenceData'              => $xqList,
            'nationalIndustrialParkData' => $cyyList,
        ], $brandData);
    }

    public static function getWgDotByCity($type, $city, $district, $status, $openScore, $settleStatus, $grade, $chosen, $name)
    {
        //容错处理
        $city = self::blurMatchCity($city);
        //通过城市code获得区
        $allDistrict = WangGuiCityByPower::getChinaDistrict();
        $cityInfo    = [];  //包含区的城市信息
        foreach ($allDistrict as $tempCity) {
            foreach ($tempCity['districts'] as $item) {
                if (mb_strpos($item['name'], $city) !== false) {
                    $cityInfo = $item;
                    break 2; // 跳出两层循环
                }
            }
        }
        //获得每个区对应的adcode
        $districtNameLists = array_column($cityInfo['districts'], 'name', 'adcode');
        $data              = [];
        switch ($type) {
            case ProgrammingEnum::PROGRAMMING_MALL:  //商场网规
                SiteLocationMallModel::query()
                    ->where('grade', '>', 0)
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('city', 'like', "%$city%");
                    })
                    ->when(mb_strlen($district), function ($query) use ($district) {
                        $query->where('district', 'like', "%$district%");
                    })
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where(function ($q) use ($name) {
                            $q->where('mallName', 'like', "%$name%")->orWhere('address', 'like', "%$name%");
                        });
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($openScore), function ($query) use ($openScore) {
                        $statusArr = explode(',', $openScore);
                        $query->whereBetween('status', $statusArr);
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('grade', $gradeArr);
                    })
                    ->when(mb_strlen($chosen), function ($query) use ($chosen) {
                        $chosenArr = explode(',', $chosen);
                        if (count($chosenArr) == 1) {
                            if ($chosen == 1) {
                                $query->where('topList', '!=', '');
                            }
                            if ($chosen == 2) {
                                $query->where('topList', '');
                            }
                        }
                    })
                    ->get()
                    ->each(function (SiteLocationMallModel $siteLocationMallModel) use (&$data, $districtNameLists) {
                        $data[] = [
                            'id'     => $siteLocationMallModel->id,
                            'type'   => ProgrammingEnum::PROGRAMMING_MALL,
                            'name'   => $siteLocationMallModel->mallName,
                            'grade'  => OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_SIFT_MAPPING[$siteLocationMallModel->grade] ?? '-',
                            'lng'    => $siteLocationMallModel->lng,
                            'lat'    => $siteLocationMallModel->lat,
                            'adcode' => (int)array_search($siteLocationMallModel->district, $districtNameLists),
                        ];
                    });
                break;
            case ProgrammingEnum::PROGRAMMING_STREET:  //街道网规
                MapNationalStreetModel::query()
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('city', 'like', "%$city%");
                    })
                    ->when(mb_strlen($district), function ($query) use ($district) {
                        $query->where('district', 'like', "%$district%");
                    })
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('address', 'like', "%$name%");
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($openScore), function ($query) use ($openScore) {
                        $statusArr = explode(',', $openScore);
                        $query->whereBetween('status', $statusArr);
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('grade', $gradeArr);
                    })
                    ->get()
                    ->each(function (MapNationalStreetModel $mapNationalStreetModel) use (&$data, $districtNameLists) {
                        $boundary = json_decode($mapNationalStreetModel->coords, true);
                        $boundary = collect($boundary)->map(function ($arr) {
                            if (2 != count($arr)) {
                                return null;
                            }
                            return [
                                'lng' => $arr[0],
                                'lat' => $arr[1],
                            ];
                        })->filter()->toArray();
                        if (mb_strpos($mapNationalStreetModel->address, $mapNationalStreetModel->name) === false) {
                            $name = $mapNationalStreetModel->name;
                        } else {
                            $name = mb_substr($mapNationalStreetModel->address, mb_strpos($mapNationalStreetModel->address, $mapNationalStreetModel->name));
                        }
                        $data[] = [
                            'id'       => $mapNationalStreetModel->id,
                            'type'     => ProgrammingEnum::PROGRAMMING_MALL,
                            'name'     => $name,
                            'grade'    => ProgrammingEnum::GRADE_MAPPING[$mapNationalStreetModel->grade] ?? '-',
                            'lng'      => $mapNationalStreetModel->lng,
                            'lat'      => $mapNationalStreetModel->lat,
                            'adcode'   => (int)array_search($mapNationalStreetModel->district, $districtNameLists),
                            'boundary' => $boundary
                        ];
                    });
                break;
            case ProgrammingEnum::PROGRAMMING_COMMUNITY:  //街道网规
                MapNationalCommunityModel::query()
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('city', 'like', "%$city%");
                    })
                    ->when(mb_strlen($district), function ($query) use ($district) {
                        $query->where('district', 'like', "%$district%");
                    })
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('address', 'like', "%$name%");
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($openScore), function ($query) use ($openScore) {
                        $statusArr = explode(',', $openScore);
                        $query->whereBetween('status', $statusArr);
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('grade', $gradeArr);
                    })
                    ->get()
                    ->each(function (MapNationalCommunityModel $mapNationalCommunityModel) use (&$data, $districtNameLists) {
                        $boundary = json_decode($mapNationalCommunityModel->coords, true);
                        $boundary = collect($boundary)->map(function ($arr) {
                            if (2 != count($arr)) {
                                return null;
                            }
                            return [
                                'lng' => $arr[0],
                                'lat' => $arr[1],
                            ];
                        })->filter()->toArray();
                        if (mb_strpos($mapNationalCommunityModel->address, $mapNationalCommunityModel->name) === false) {
                            $name = $mapNationalCommunityModel->name;
                        } else {
                            $name = mb_substr($mapNationalCommunityModel->address, mb_strpos($mapNationalCommunityModel->address, $mapNationalCommunityModel->name));
                        }
                        $data[] = [
                            'id'       => $mapNationalCommunityModel->id,
                            'type'     => ProgrammingEnum::PROGRAMMING_MALL,
                            'name'     => $name,
                            'grade'    => ProgrammingEnum::GRADE_MAPPING[$mapNationalCommunityModel->grade] ?? '-',
                            'lng'      => $mapNationalCommunityModel->lng,
                            'lat'      => $mapNationalCommunityModel->lat,
                            'adcode'   => (int)array_search($mapNationalCommunityModel->district, $districtNameLists),
                            'boundary' => $boundary
                        ];
                    });
                break;
            case ProgrammingEnum::PROGRAMMING_TOWN:  //乡镇网规
                MapTownshipPlanAreaModel::query()
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('city', 'like', "%$city%");
                    })
                    ->when(mb_strlen($district), function ($query) use ($district) {
                        $query->where('district', 'like', "%$district%");
                    })
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('area', 'like', "%$name%");
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($openScore), function ($query) use ($openScore) {
                        $statusArr = explode(',', $openScore);
                        $query->whereBetween('status', $statusArr);
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('grade', $gradeArr);
                    })
                    ->when(mb_strlen($chosen), function ($query) use ($chosen) {
                        $chosenArr = explode(',', $chosen);
                        if (count($chosenArr) == 1) {
                            if ($chosen == 1) {
                                $query->where('qianqiangTownRank', '!=', 0);
                            }
                            if ($chosen == 2) {
                                $query->where('qianqiangTownRank', 0);
                            }
                        }
                    })
                    ->get()
                    ->each(function (MapTownshipPlanAreaModel $mapTownshipPlanAreaModel) use (&$data, $districtNameLists) {

                        // 组数据
                        $data[] = [
                            'id'     => $mapTownshipPlanAreaModel->id,
                            'type'   => ProgrammingEnum::PROGRAMMING_TOWN,
                            'name'   => $mapTownshipPlanAreaModel->area,
                            'grade'  => ProgrammingEnum::GRADE_MAPPING[$mapTownshipPlanAreaModel->grade] ?? '-',
                            'lng'    => $mapTownshipPlanAreaModel->lng,
                            'lat'    => $mapTownshipPlanAreaModel->lat,
                            'adcode' => (int)array_search($mapTownshipPlanAreaModel->district, $districtNameLists),
                        ];
                    });
                break;
            case ProgrammingEnum::PROGRAMMING_SCHOOL:  //学校网规
                MapNationalUniversitiesModel::query()
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('city', 'like', "%$city%");
                    })
                    ->when(mb_strlen($district), function ($query) use ($district) {
                        $query->where('district', 'like', "%$district%");
                    })
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where(function ($q) use ($name) {
                            $q->where('name', 'like', "%$name%")->orWhere('address', 'like', "%$name%");
                        });
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($openScore), function ($query) use ($openScore) {
                        $statusArr = explode(',', $openScore);
                        $query->whereBetween('status', $statusArr);
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('grade', $gradeArr);
                    })
                    ->when(mb_strlen($chosen), function ($query) use ($chosen) {
                        $chosenArr = explode(',', $chosen);
                        if (count($chosenArr) != 3) {
                            if (in_array(1, $chosenArr)) {
                                $query->where('project985', '是');
                            }
                            if (in_array(2, $chosenArr)) {
                                $query->where('project211', '是');
                            }
                            if (in_array(3, $chosenArr)) {
                                $query->where('strongBasis', '是');
                            }
                        }
                    })
                    ->get()
                    ->each(function (MapNationalUniversitiesModel $mapNationalUniversitiesModel) use (&$data, $districtNameLists) {
                        $boundary = [];
                        if (!empty($mapNationalUniversitiesModel->boundary)) {
                            $boundary = json_decode($mapNationalUniversitiesModel->boundary, true);
                            $boundary = collect($boundary)->map(function ($arr) {
                                if (2 != count($arr)) {
                                    return null;
                                }
                                return [
                                    'lng' => $arr[0],
                                    'lat' => $arr[1],
                                ];
                            })->filter()->toArray();
                        }
                        $data[] = [
                            'id'     => $mapNationalUniversitiesModel->id,
                            'type'   => ProgrammingEnum::PROGRAMMING_SCHOOL,
                            'name'   => $mapNationalUniversitiesModel->name,
                            'grade'  => ProgrammingEnum::GRADE_MAPPING[$mapNationalUniversitiesModel->grade] ?? '-',
                            'lng'    => $mapNationalUniversitiesModel->lon,
                            'lat'    => $mapNationalUniversitiesModel->lat,
                            'adcode' => (int)array_search($mapNationalUniversitiesModel->district, $districtNameLists),
                            'boundary' => $boundary
                        ];
                    });
                break;
            case ProgrammingEnum::PROGRAMMING_INDUSTRIAL_PARKS:  //产业园区网规
                MapNationalIndustrialParkModel::query()
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('city', 'like', "%$city%");
                    })
                    ->when(mb_strlen($district), function ($query) use ($district) {
                        $query->where('district', 'like', "%$district%");
                    })
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('name', 'like', "%$name%");
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($openScore), function ($query) use ($openScore) {
                        $statusArr = explode(',', $openScore);
                        $query->whereBetween('status', $statusArr);
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('grade', $gradeArr);
                    })
                    ->get()
                    ->each(function (MapNationalIndustrialParkModel $mapNationalIndustrialParkModel) use (&$data, $districtNameLists) {
                        $data[] = [
                            'id'     => $mapNationalIndustrialParkModel->id,
                            'type'   => ProgrammingEnum::PROGRAMMING_INDUSTRIAL_PARKS,
                            'name'   => $mapNationalIndustrialParkModel->name,
                            'grade'  => ProgrammingEnum::GRADE_MAPPING[$mapNationalIndustrialParkModel->grade] ?? '-',
                            'lng'    => $mapNationalIndustrialParkModel->lon,
                            'lat'    => $mapNationalIndustrialParkModel->lat,
                            'adcode' => (int)array_search($mapNationalIndustrialParkModel->district, $districtNameLists),
                        ];
                    });
                break;
            default:
                self::throwErr('网规类型错误');
        }
        $centerPoint = CityTerritorialBoundaryModel::query()
            ->where('level', 'city')
            ->where('name', 'like', "%$city%")
            ->select(['id', 'name', 'centerLongitude', 'centerLatitude', 'boundary'])
            ->first();
        $boundary    = [];

        if ($centerPoint) {
            $boundary = json_decode($centerPoint->boundary, true);
        }


        return [
            'list'            => $data,
            'centerLongitude' => (float)optional($centerPoint)->centerLongitude,
            'centerLatitude'  => (float)optional($centerPoint)->centerLatitude,
            'boundary'        => (object)$boundary,
        ];
    }

    /**
     * @throws GuzzleException
     */
    public static function dotEvaluate($id, $type, $openPotential, $content, $flowScore, $flowFile, $businessFile, $customerGroupType, $passengerFlowDrive, $canOpenArea, $overallMovingLine, $takeawayEvaluation, $floorGuidance, $rmsUserName, $rmsUserId, $evaluateId, $evaluateTime)
    {
        //根据ID和type 获得编号
        $orderNo = '';
        switch ($type) {
            case ProgrammingEnum::PROGRAMMING_MALL:
                $wgModel    = SiteLocationMallModel::query()
                    ->where('grade', '>', 0)
                    ->where('id', $id);
                $orderNo    = (string)$wgModel->value('wgNumber');
                $wgModel    = $wgModel->first();
                $AreaPrefix = $wgModel->province . '-' . $wgModel->city . '-' . $wgModel->district;
                $address    = $wgModel->address;
                $grade      = $wgModel->grade;
                $name       = $wgModel->mallName;
                $lng        = $wgModel->lng;
                $lat        = $wgModel->lat;
                break;
            case ProgrammingEnum::PROGRAMMING_STREET:
                $wgModel    = MapNationalStreetModel::query()->where('id', $id);
                $orderNo    = (string)$wgModel->value('wgNumber');
                $wgModel    = $wgModel->first();
                $AreaPrefix = $wgModel->province . '-' . $wgModel->city . '-' . $wgModel->district;
                $address    = $wgModel->address;
                $grade      = $wgModel->grade;
                $lng        = $wgModel->lng;
                $lat        = $wgModel->lat;
                if (mb_strpos($wgModel->address, $wgModel->name) === false) {
                    $name = $wgModel->name;
                } else {
                    $name = mb_substr($wgModel->address, mb_strpos($wgModel->address, $wgModel->name));
                }
                break;
            case ProgrammingEnum::PROGRAMMING_COMMUNITY:
                $wgModel    = MapNationalCommunityModel::query()->where('id', $id);
                $orderNo    = (string)$wgModel->value('wgNumber');
                $wgModel    = $wgModel->first();
                $AreaPrefix = $wgModel->province . '-' . $wgModel->city . '-' . $wgModel->district;
                $address    = $wgModel->address;
                $grade      = $wgModel->grade;
                $lng        = $wgModel->lng;
                $lat        = $wgModel->lat;
                $name       = $wgModel->name;
                break;
            case ProgrammingEnum::PROGRAMMING_TOWN:
                $wgModel    = MapTownshipPlanAreaModel::query()->where('id', $id);
                $orderNo    = (string)$wgModel->value('wgNumber');
                $wgModel    = $wgModel->first();
                $AreaPrefix = $wgModel->province . '-' . $wgModel->city . '-' . $wgModel->district;
                $address    = $wgModel->address;
                $grade      = $wgModel->grade;
                $name       = $wgModel->area;
                $lng        = $wgModel->lng;
                $lat        = $wgModel->lat;
                break;
            case ProgrammingEnum::PROGRAMMING_SCHOOL:
                $wgModel    = MapNationalUniversitiesModel::query()->where('id', $id);
                $orderNo    = (string)$wgModel->value('wgNumber');
                $wgModel    = $wgModel->first();
                $AreaPrefix = $wgModel->province . '-' . $wgModel->city . (mb_strlen($wgModel->district) ? ('-' . $wgModel->district) : '');
                $address    = $wgModel->address;
                $grade      = $wgModel->grade;
                $name       = $wgModel->name;
                $lng        = $wgModel->lon;
                $lat        = $wgModel->lat;
                break;
            case ProgrammingEnum::PROGRAMMING_INDUSTRIAL_PARKS:
                $wgModel    = MapNationalIndustrialParkModel::query()->where('id', $id);
                $orderNo    = (string)$wgModel->value('wgNumber');
                $wgModel    = $wgModel->first();
                $AreaPrefix = $wgModel->province . '-' . $wgModel->city . $wgModel->district;
                $address    = $wgModel->address;
                $grade      = $wgModel->grade;
                $name       = $wgModel->name;
                $lng        = $wgModel->lon;
                $lat        = $wgModel->lat;
                break;
            default:
                self::throwErr('网规类型不存在,请联系相关负责人');
        }

        if (!mb_strlen($orderNo)) {
            self::throwErr('未找到网规编号');
        }
        //通过经纬度获得天气和温度

        $key      = WangGuiCityByPower::getRandomAmapKey();
        $areaRes  = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
            ->get(sprintf(config('area.amapGetDistrictByLatLng'), $lng, $lat, $key))
            ->json();
        $adcode   = $areaRes['regeocode']['addressComponent']['adcode'] ?? 0;
        $province = $areaRes['regeocode']['addressComponent']['province'] ?? '';
        $ext      = [];
        if ($adcode) {
            $weatherRes     = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
                ->get(sprintf(config('weather.amapWeatherUrl'), $adcode, $key))
                ->json();
            $ext['weather'] = ($weatherRes['lives'][0]['weather'] ?? '') . ' ' . (($weatherRes['lives'][0]['temperature'] ?? '') ? ($weatherRes['lives'][0]['temperature'] . '℃') : '');
        }
        $ext['wgName'] = $name;

        if ($openPotential >= ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE) {
            $status = ProgrammingEnum::STATUS_EVALUATED_OK;
        } else {
            $status = ProgrammingEnum::STATUS_EVALUATED_NO;
        }

        //点位评估时间
        $evaluateTime = strlen($evaluateTime) ? strtotime($evaluateTime) : time();
        //获得最新的评估记录
        $siteLocationExamineLogModel = OpenShopSiteLocationExamineLogModel::query()
            ->where('orderNo', $orderNo)
            ->with(['wangguiSiteDistrictRel'])
            ->orderByDesc('updatedAt');
        //第二选择状态
        $secondLogModel = $siteLocationExamineLogModel->skip(1)->first();
        $newTimeModel   = $siteLocationExamineLogModel->first();
        if ($newTimeModel != null) {
            $newTime              = $newTimeModel->updatedAt->timestamp;
            $newStatus            = $newTimeModel->openPotential;
            $haveOpenDistrictList = $newTimeModel->wangguiSiteDistrictRel->pluck('id')->toArray();
        } else {
            $newTime              = 0;
            $newStatus            = 0;
            $haveOpenDistrictList = [];
        }

        if ($evaluateId == ($haveOpenDistrictList[0] ?? -1)) {
            if ($secondLogModel && $secondLogModel->updatedAt->timestamp > $evaluateTime) {
                $wgModel->update([
                    'status' => $secondLogModel->openPotential,
                ]);
            } else {
                $wgModel->update([
                    'status' => $openPotential,
                ]);
            }
        } else {
            $wgModel->update([
                'status' => $newTime <= $evaluateTime ? $openPotential : $newStatus,
            ]);
        }

        if ($newTime < $evaluateTime) {
            //全部置为旧的
            OpenShopSiteLocationExamineLogModel::query()
                ->where('orderNo', $orderNo)
                ->where('createdByUid', $rmsUserId)
                ->update([
                    'isToStore' => OpenShopSiteLocationExamineLogModel::IS_NEW_NO,
                    'updatedAt' => DB::raw('`updatedAt`')
                ]);
        }

        if ($evaluateId) {
            //获得该用户对于此网规点位的评论
            $auditModel = OpenShopSiteLocationExamineLogModel::query()
                ->where('createdByUid', $rmsUserId)
                ->orderByDesc('updatedAt')
                ->where('orderNo', $orderNo);
            if ($evaluateId == $auditModel->first()->id) {
                if ($auditModel->skip(1)->first() && $evaluateTime < $auditModel->skip(1)->first()->updatedAt->timestamp) {
                    $secondUserAudit             = $auditModel->skip(1)->first();
                    $secondUserAudit->isToStore  = OpenShopSiteLocationExamineLogModel::IS_TO_STORE_YES;
                    $secondUserAudit->timestamps = false;
                    $secondUserAudit->save();
                    $isToStore = OpenShopSiteLocationExamineLogModel::IS_TO_STORE_NO;
                } else {
                    $isToStore = OpenShopSiteLocationExamineLogModel::IS_TO_STORE_YES;
                }
            } else {
                $isToStore = OpenShopSiteLocationExamineLogModel::IS_TO_STORE_NO;
            }


            $examine = OpenShopSiteLocationExamineLogModel::query()->find($evaluateId);
            if (null == $examine) {
                self::throwErr('获取评价内容出错');
            }
            if ($examine->createdByUid != $rmsUserId) {
                self::throwErr('暂无修改权限');
            }
            //删除资源
            ResourcesModel::query()
                ->where('businessId', $evaluateId)
                ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
                ->where('business', ResourcesModel::BUSINESS_WG_AUDIT)
                ->orWhere('business', ResourcesModel::BUSINESS_OPEN_DISTRICT)
                ->update([
                    "isDeleted" => 1
                ]);
            $examine->timestamps         = false;
            $examine->content            = $content;
            $examine->extra              = json_encode($ext, JSON_UNESCAPED_UNICODE);
            $examine->isToStore          = $isToStore;
            $examine->status             = $status;
            $examine->updatedAt          = $evaluateTime;
            $examine->flowOfPeopleScores = $flowScore;
            $examine->openPotential      = $openPotential;
            $examine->passengerFlowDrive = implode(',', $passengerFlowDrive);
            $examine->customerGroupType  = implode(',', $customerGroupType);
            $examine->save();
        } else {
            $examine = (new OpenShopSiteLocationExamineLogModel([
                'orderNo'            => $orderNo,
                'source'             => OpenShopSiteLocationExamineLogModel::SOURCE_WG_AUDIT,
                'content'            => $content,
                'isToStore'          => $newTime > $evaluateTime ? OpenShopSiteLocationExamineLogModel::IS_NEW_NO : OpenShopSiteLocationExamineLogModel::IS_NEW_YES,
                'status'             => $status,
                'type'               => $type,
                'extra'              => json_encode($ext, JSON_UNESCAPED_UNICODE),
                'createdByUid'       => $rmsUserId,
                'updatedByUid'       => $rmsUserId,
                'updatedAt'          => $evaluateTime,
                'openPotential'      => $openPotential,
                'flowOfPeopleScores' => $flowScore,
                'passengerFlowDrive' => implode(',', $passengerFlowDrive),
                'customerGroupType'  => implode(',', $customerGroupType),
            ]))->addData();
        }
        $imgKey   = [];
        $imageArr = [];
        //文件入库
        //图片计数
        $thumbnail = [];
        if (count($businessFile)) {
            foreach ($businessFile as $file) {
                //上传图片用于飞书通知展示
                if ($file['type'] == 'image' && count($thumbnail) <= 9) {
                    $thumbnail[] = self::getFeishuImageKey($file['url']);
                }
                if ($file['type'] == 'video') {
                    self::joinUploadTranscoding(
                        $examine->id,
                        ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        ResourcesModel::BUSINESS_WG_AUDIT,
                        ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION,
                        $file['type'],
                        $file['url'],
                        ResourcesModel::IS_PUBLIC_YES,
                        $rmsUserId
                    );
                } else {
                    $imageArr[] = [
                        'businessId'   => $examine->id,
                        'module'       => ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        'business'     => ResourcesModel::BUSINESS_WG_AUDIT,
                        'name'         => ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION,
                        'url'          => ltrim(parse_url($file['url'], PHP_URL_PATH), '/'),
                        'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                        'extra'        => json_encode(['type' => $file['type']], JSON_UNESCAPED_UNICODE),
                        'createdByUid' => $rmsUserId,
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            }
        }

        if (count($flowFile)) {
            foreach ($flowFile as $file) {
                //上传图片用于飞书通知展示
                if ($file['type'] == 'image' && count($thumbnail) <= 9) {
                    $thumbnail[] = self::getFeishuImageKey($file['url']);
                }
                if ($file['type'] == 'video') {
                    self::joinUploadTranscoding(
                        $examine->id,
                        ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        ResourcesModel::BUSINESS_WG_AUDIT,
                        ProgrammingEnum::WANGGUI_FLOW_OF_PEOPLE,
                        $file['type'],
                        $file['url'],
                        ResourcesModel::IS_PUBLIC_YES,
                        $rmsUserId
                    );
                } else {
                    $imageArr[] = [
                        'businessId'   => $examine->id,
                        'module'       => ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        'business'     => ResourcesModel::BUSINESS_WG_AUDIT,
                        'name'         => ProgrammingEnum::WANGGUI_FLOW_OF_PEOPLE,
                        'url'          => ltrim(parse_url($file['url'], PHP_URL_PATH), '/'),
                        'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                        'extra'        => json_encode(['type' => $file['type']], JSON_UNESCAPED_UNICODE),
                        'createdByUid' => $rmsUserId,
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            }
        }

        //$overallMovingLine, $takeawayEvaluation, $floorGuidance,
        if (count($overallMovingLine)) {
            foreach ($overallMovingLine as $file) {
                //上传图片用于飞书通知展示
                if ($file['type'] == 'image' && count($thumbnail) <= 9) {
                    $thumbnail[] = self::getFeishuImageKey($file['url']);
                }
                if ($file['type'] == 'video') {
                    self::joinUploadTranscoding(
                        $examine->id,
                        ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        ResourcesModel::BUSINESS_WG_AUDIT,
                        ProgrammingEnum::WANGGUI_OVERALL_MOVING_LINE,
                        $file['type'],
                        $file['url'],
                        ResourcesModel::IS_PUBLIC_YES,
                        $rmsUserId
                    );
                } else {
                    $imageArr[] = [
                        'businessId'   => $examine->id,
                        'module'       => ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        'business'     => ResourcesModel::BUSINESS_WG_AUDIT,
                        'name'         => ProgrammingEnum::WANGGUI_OVERALL_MOVING_LINE,
                        'url'          => ltrim(parse_url($file['url'], PHP_URL_PATH), '/'),
                        'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                        'extra'        => json_encode(['type' => $file['type']], JSON_UNESCAPED_UNICODE),
                        'createdByUid' => $rmsUserId,
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            }
        }
        if (count($takeawayEvaluation)) {
            foreach ($takeawayEvaluation as $file) {
                //上传图片用于飞书通知展示
                if ($file['type'] == 'image' && count($thumbnail) <= 9) {
                    $thumbnail[] = self::getFeishuImageKey($file['url']);
                }
                if ($file['type'] == 'video') {
                    self::joinUploadTranscoding(
                        $examine->id,
                        ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        ResourcesModel::BUSINESS_WG_AUDIT,
                        ProgrammingEnum::WANGGUI_TAKEAWAY_EVALUATION,
                        $file['type'],
                        $file['url'],
                        ResourcesModel::IS_PUBLIC_YES,
                        $rmsUserId
                    );
                } else {
                    $imageArr[] = [
                        'businessId'   => $examine->id,
                        'module'       => ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        'business'     => ResourcesModel::BUSINESS_WG_AUDIT,
                        'name'         => ProgrammingEnum::WANGGUI_TAKEAWAY_EVALUATION,
                        'url'          => ltrim(parse_url($file['url'], PHP_URL_PATH), '/'),
                        'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                        'extra'        => json_encode(['type' => $file['type']], JSON_UNESCAPED_UNICODE),
                        'createdByUid' => $rmsUserId,
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            }
        }
        if (count($floorGuidance)) {
            foreach ($floorGuidance as $file) {
                //上传图片用于飞书通知展示
                if ($file['type'] == 'image' && count($thumbnail) <= 9) {
                    $thumbnail[] = self::getFeishuImageKey($file['url']);
                }
                if ($file['type'] == 'video') {
                    self::joinUploadTranscoding(
                        $examine->id,
                        ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        ResourcesModel::BUSINESS_WG_AUDIT,
                        ProgrammingEnum::WANGGUI_FIOOR_GUIDANCE,
                        $file['type'],
                        $file['url'],
                        ResourcesModel::IS_PUBLIC_YES,
                        $rmsUserId
                    );
                } else {
                    $imageArr[] = [
                        'businessId'   => $examine->id,
                        'module'       => ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        'business'     => ResourcesModel::BUSINESS_WG_AUDIT,
                        'name'         => ProgrammingEnum::WANGGUI_FIOOR_GUIDANCE,
                        'url'          => ltrim(parse_url($file['url'], PHP_URL_PATH), '/'),
                        'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                        'extra'        => json_encode(['type' => $file['type']], JSON_UNESCAPED_UNICODE),
                        'createdByUid' => $rmsUserId,
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            }
        }
        ResourcesModel::query()->insert($imageArr);

        if (count($canOpenArea)) {
            //修改的id
            $updateIds = collect($canOpenArea)->pluck('id')->filter()->toArray();
            WangguiSiteDistrictModel::query()
                ->whereIn('id', array_diff($haveOpenDistrictList, $updateIds))
                ->update([
                    'isDeleted' => 1
                ]);
            //对于可开区域的调整
            foreach ($canOpenArea as $canOpen) {
                if (isset($canOpen['id'])) {
                    $openAreaModel = WangguiSiteDistrictModel::query()->find($canOpen['id']);
                } else {
                    $openAreaModel = new WangguiSiteDistrictModel();
                }
                $openAreaModel->relationId  = $examine->id;
                $openAreaModel->name        = $canOpen['name'];
                $openAreaModel->isEmptyShop = $canOpen['isEmptyShop'];
                $openAreaModel->save();
                $resourceArr = [];
                foreach ($canOpen['file'] as $file) {
                    if ($file['type'] == 'video') {
                        self::joinUploadTranscoding(
                            $openAreaModel->id,
                            ResourcesModel::MODULE_TYPE_WG_AUDIT,
                            ResourcesModel::BUSINESS_OPEN_DISTRICT,
                            ProgrammingEnum::WANGGUI_OPEN_DISTRICT,
                            $file['type'],
                            $file['url'],
                            ResourcesModel::IS_PUBLIC_YES,
                            $rmsUserId
                        );
                    } else {
                        $resourceArr[] = [
                            'businessId'   => $openAreaModel->id,
                            'module'       => ResourcesModel::MODULE_TYPE_WG_AUDIT,
                            'business'     => ResourcesModel::BUSINESS_OPEN_DISTRICT,
                            'name'         => ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION,
                            'url'          => ltrim(parse_url($file['url'], PHP_URL_PATH), '/'),
                            'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                            'extra'        => json_encode(['type' => $file['type']], JSON_UNESCAPED_UNICODE),
                            'createdByUid' => $rmsUserId,
                            'updatedByUid' => $rmsUserId,
                        ];
                    }
                }
                ResourcesModel::query()->insert($resourceArr);
            }
        } else {
            WangguiSiteDistrictModel::query()
                ->where('relationId', $evaluateId)
                ->update([
                    'isDeleted' => 1
                ]);
        }

        $areaRobotJson = ConfigModel::query()
            ->where('module', 'wanggui')
            ->where('name', 'areaRobots')
            ->value('value');
        $areaRobotArr  = json_decode($areaRobotJson, true);
        $robotConfig   = [
            'token'  => config('feishu.robots.wangguiAudit.urlToken'),
            'secret' => config('feishu.robots.wangguiAudit.token')
        ];
        foreach ($areaRobotArr as $area => $robot) {
            $provinceLen = mb_strlen($area);
            if (mb_substr($province, 0, $provinceLen) == $area) {
                $robotConfig['token']  = substr($robot['webhook'], (strripos($robot['webhook'], '/') + 1));
                $robotConfig['secret'] = $robot['sign'];
            }
        }

        $json = json_decode(
            sprintf(
                file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/wangguiAudit.json')),
                $rmsUserName,
                $AreaPrefix,
                formatDate($evaluateTime),
                $ext['weather'] ?? '-',
                $openPotential,
                $flowScore,
                \App\Service\OpenShop\Feishu\BaseService::getWangguiAppletUrl($type, $id),
                $status == ProgrammingEnum::STATUS_EVALUATED_OK ? 'green' : 'red',
                '【评估' . (ProgrammingEnum::STATUS_MAPPING[$status] ?? '-') . '】 [' . ProgrammingEnum::PROGRAMMING_MAPPING[$type] . '-' . ProgrammingEnum::GRADE_MAPPING[$grade] . ' ' . $name . '] 点位评估可开潜力值' . $openPotential . '，请注意',
            ), true
        );


        //获得行
        $rawCount = (int)ceil(count($thumbnail) / 3);

        //获得行图片组件
        $rawPictureComponent = json_decode(file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/threeRawPictureComponent.json')), true);

        //获得单图片
        $singlePictureComponent = json_decode(file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/singlePictureComponent.json')), true);


        $temp   =    [];
        collect($thumbnail)->each(function ($item) use ($singlePictureComponent, &$temp) {
            $singlePictureComponent['extra']['img_key'] = $item;
            if ($item != 'img_v2_041b28e3-5680-48c2-9af2-497ace79333g') {
                $temp[] = $singlePictureComponent;
            }
        })->toArray();
        $totalImage = [];
        for ($i = 0; $i < $rawCount; $i++) {
            $tempRaw                             = $rawPictureComponent;
            $key                                 = $i * 3;
            $tempRaw['columns'][0]['elements'][] = $temp[$key];
            isset($temp[$key + 1]) ? ($tempRaw['columns'][1]['elements'][] = $temp[$key + 1]) : ($a['columns'][1]['elements'] = []);
            isset($temp[$key + 2]) ? ($tempRaw['columns'][2]['elements'][] = $temp[$key + 2]) : ($a['columns'][2]['elements'] = []);
            $totalImage[] = $tempRaw;
        }
        $json['elements'][3]['columns'][0]['elements'] = $totalImage;
        $json['elements'][4]['text']['content']        .= $content;


        if (config('app.env') == 'prod') {
            Factory::feiShu()
                ->setToken($robotConfig['token'])
                ->setSecret($robotConfig['secret'])
                ->setMessage(new \Guanguans\Notify\Messages\FeiShu\CardMessage($json))
                ->send();
        }
        if ($robotConfig['token'] != config('feishu.robots.wangguiAudit.urlToken')) {
            Factory::feiShu()
                ->setToken(config('feishu.robots.wangguiAudit.urlToken'))
                ->setSecret(config('feishu.robots.wangguiAudit.token'))
                ->setMessage(new \Guanguans\Notify\Messages\FeiShu\CardMessage($json))
                ->send();
        }
    }

    public static function capacity(
        $type, $city, $sort, $status, $settleStatus, $grade, $chosen, $name, bool $isKms, bool $isOwn, array $userInfo, int $provinceCode, int $cityCode, int $districtCode
    ): array
    {
        //容错处理
        $city = self::blurMatchCity($city);
        //初始化
        $totalCount = 0;  //总量
        $passCount  = 0;  //可用数量
        $waitCount  = 0;  //待评估
        $enterCount = 0;  //评估通过未入驻
        $statusData = $statusArr = $provinceCodes = $cityCodes = $districtCodes = $userInfos = [];
        $role = 0;
        if ($isKms) {
            $city = '';//运营新接口用省市区code查询
            if (mb_strlen($status)) {
                $statusArr = explode(',', $status);
                foreach ($statusArr as $v) {
                    $temp = ProgrammingEnum::WG_AND_TASK_STATUS_MAPPING[$v] ?? [];
                    if ($temp) {
                        $statusData = array_merge($statusData, $temp);
                    }
                }
                $status = '';
            }

            // 查询用户身份权限
            $getUserRole  = UserRoleService::getUserRole($userInfo['userId']);
            $role         = $getUserRole['role'] ?? UserRoleService::ROLE_SPECIAL_NO_ACCESS;
            $allArea      = $getUserRole['userResponsibleArea']['all'] ?? false;
            $branchOffice = $getUserRole['homeBranchOffice']['branchOffice'] ?? [];

            if (!$allArea && $branchOffice && !$provinceCode && !$cityCode && !$districtCode) {//获取对应分公司id
                $branchIds     = array_column($branchOffice, 'id');
                $getRegionInfo = OpenShopOrganizationRegionMappingModel::getRegionInfo($branchIds);
                if ($getRegionInfo) {
                    $provinceCodes = array_column($getRegionInfo, 'provinceCode');
                }
            }
            if ($allArea || in_array($role, [UserRoleService::ROLE_BASE_KAM])) {
                $provinceCodes = $cityCodes = $districtCodes = [];
            }

//            $userInfos = KmsUser::getUserInfo([], '选址开发中心');//大客户部用户信息
        }
        if ($provinceCode) {
            $provinceCodes = [$provinceCode];
        }
        if ($cityCode) {
            $cityCodes = [$cityCode];
        }
        if ($districtCode) {
            $districtCodes = [$districtCode];
        }
        $clueTotal    = 0;//有线索
        $houseTotal   = 0;//有房源
        $settledTotal = 0;//已入驻

        switch ($type) {
            case ProgrammingEnum::PROGRAMMING_MALL:  //商场网规
                $list = SiteLocationMallModel::query()
                    ->leftJoin('customer_department_task', 'customer_department_task.wgNumber', '=', 'site_location_mall.wgNumber')
                    ->when(
                        ($isOwn || $statusArr) && $isKms, function ($query) use ($statusData, $statusArr, $isOwn, $userInfo) {
                        $query->when(
                            $isOwn && $userInfo, function ($query) use ($userInfo) {
                            $query->where('customer_department_task.assignId', $userInfo['userId'] ?? 0);//只看自己的
                        }
                        )->when(
                            $statusArr, function ($query) use ($statusData, $statusArr) {
                            $query->where(
                                function ($query) use ($statusData, $statusArr) {
                                    $query->when(
                                        $statusData, function ($query) use ($statusData) {
                                        $query->whereIn('customer_department_task.projectPhase', $statusData);//关联项目阶段状态
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && $statusData, function ($query) use ($statusArr) {
                                        $query->orWhere(
                                            function ($query) use ($statusArr) {
                                                $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                                ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                            }
                                        );
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && !$statusData, function ($query) use ($statusArr) {
                                        $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                        ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                    }
                                    );
                                }
                            );
                        }
                        );
                    }
                    )
                    ->where('site_location_mall.grade', '>', 0)
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('site_location_mall.city', 'like', "%$city%");
                    })
                    ->when(
                        $provinceCodes, function ($query) use ($provinceCodes) {
                        $query->whereIn('site_location_mall.provinceCode', $provinceCodes);
                    }
                    )
                    ->when(
                        $cityCodes, function ($query) use ($cityCodes) {
                        $query->whereIn('site_location_mall.cityCode', $cityCodes);
                    }
                    )
                    ->when(
                        $districtCodes, function ($query) use ($districtCodes) {
                        $query->whereIn('site_location_mall.districtCode', $districtCodes);
                    }
                    )
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('site_location_mall.status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('site_location_mall.status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('site_location_mall.mallName', 'like', "%$name%");
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('site_location_mall.settle', $settleStatus);
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('site_location_mall.grade', $gradeArr);
                    })
                    ->when(mb_strlen($chosen), function ($query) use ($chosen) {
                        $chosenArr = explode(',', $chosen);
                        if (count($chosenArr) == 1) {
                            if ($chosen == 1) {
                                $query->where('site_location_mall.topList', '!=', '');
                            }
                            if ($chosen == 2) {
                                $query->where('site_location_mall.topList', '');
                            }
                        }
                    })->select(['site_location_mall.status','site_location_mall.shopNum','site_location_mall.settle','customer_department_task.projectPhase'])
                    ->get();

                $totalCount = $list->count();
                if ($isKms) {
                    $clueTotal    = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE)->count();
                    $houseTotal   = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE)->count();
                    $settledTotal = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM)->count();
                } else {
                    $waitCount  = $list->where('status', ProgrammingEnum::STATUS_WAIT_EVALUATE)->count();
                    $passCount  = $list->where('status', '>=', ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE)->count();
                    $enterCount = $list->where('status', '>=', ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE)
                        ->where('shopNum', 0)
                        ->count();
                }
//
//                   ->each(function (SiteLocationMallModel $siteLocationMallModel) use (&$houseTotal, &$clueTotal, &$settledTotal, &$totalCount, &$passCount, &$waitCount, &$enterCount) {
//                        $totalCount++;
//                        if ($siteLocationMallModel->status == ProgrammingEnum::STATUS_WAIT_EVALUATE) {
//                            $waitCount++;
//                        }
//                        if ($siteLocationMallModel->status >= ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE) {
//                            $passCount++;
//                        }
//                        if ($siteLocationMallModel->status >= ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE && $siteLocationMallModel->shopNum == 0) {
//                            $enterCount++;
//                        }
//                        $projectPhase = $siteLocationMallModel->projectPhase ?? 0;
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE) {
//                            $clueTotal++;// 有线索
//                        }
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE) {
//                            $houseTotal++;// 有房源
//                        }
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM) {
//                            $settledTotal++;// 已入驻
//                        }
//                    });
                break;
            case ProgrammingEnum::PROGRAMMING_STREET:  //街道网规
                $list = MapNationalStreetModel::query()
                    ->leftJoin('customer_department_task', 'customer_department_task.wgNumber', '=', 'map_national_streets.wgNumber')
                    ->when(
                        ($isOwn || $statusArr) && $isKms, function ($query) use ($statusData, $statusArr, $isOwn, $userInfo) {
                        $query->when(
                            $isOwn && $userInfo, function ($query) use ($userInfo) {
                            $query->where('customer_department_task.assignId', $userInfo['userId'] ?? 0);//只看自己的
                        }
                        )->when(
                            $statusArr, function ($query) use ($statusData, $statusArr) {
                            $query->where(
                                function ($query) use ($statusData, $statusArr) {
                                    $query->when(
                                        $statusData, function ($query) use ($statusData) {
                                        $query->whereIn('customer_department_task.projectPhase', $statusData);//关联项目阶段状态
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && $statusData, function ($query) use ($statusArr) {
                                        $query->orWhere(
                                            function ($query) use ($statusArr) {
                                                $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                                ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                            }
                                        );
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && !$statusData, function ($query) use ($statusArr) {
                                        $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                        ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                    }
                                    );
                                }
                            );
                        }
                        );
                    }
                    )
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('map_national_streets.city', 'like', "%$city%");
                    })
                    ->when(
                        $provinceCodes, function ($query) use ($provinceCodes) {
                        $query->whereIn('map_national_streets.provinceCode', $provinceCodes);
                    }
                    )
                    ->when(
                        $cityCodes, function ($query) use ($cityCodes) {
                        $query->whereIn('map_national_streets.cityCode', $cityCodes);
                    }
                    )
                    ->when(
                        $districtCodes, function ($query) use ($districtCodes) {
                        $query->whereIn('map_national_streets.districtCode', $districtCodes);
                    }
                    )
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('map_national_streets.name', 'like', "%$name%");
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('map_national_streets.settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_streets.status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_streets.status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('map_national_streets.grade', $gradeArr);
                    })
                    ->select(['map_national_streets.status','map_national_streets.shopNum','map_national_streets.settle','customer_department_task.projectPhase'])
                    ->get();

                $totalCount = $list->count();
                if ($isKms) {
                    $clueTotal    = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE)->count();// 有线索
                    $houseTotal   = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE)->count();// 有房源
                    $settledTotal = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM)->count();// 已入驻
                } else {
                    $waitCount  = $list->where('status', ProgrammingEnum::STATUS_WAIT_EVALUATE)->count();
                    $passCount  = $list->where('status', '>=',  ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE)->count();
                    $enterCount = $list->where('status', '>=',  ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE)
                        ->where('shopNum', 0)
                        ->count();
                }
//                    ->each(function (MapNationalStreetModel $mapNationalStreetModel) use (&$settledTotal, &$houseTotal, &$clueTotal, &$totalCount, &$passCount, &$waitCount, &$enterCount) {
//                        $totalCount++;
//                        if ($mapNationalStreetModel->status == ProgrammingEnum::STATUS_WAIT_EVALUATE) {
//                            $waitCount++;
//                        }
//                        if ($mapNationalStreetModel->status >= ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE) {
//                            $passCount++;
//                        }
//                        if ($mapNationalStreetModel->status >= ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE && $mapNationalStreetModel->shopNum == 0) {
//                            $enterCount++;
//                        }
//                        $projectPhase = $mapNationalStreetModel->projectPhase ?? 0;
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE) {
//                            $clueTotal++;// 有线索
//                        }
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE) {
//                            $houseTotal++;// 有房源
//                        }
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM) {
//                            $settledTotal++;// 已入驻
//                        }
//                    });
                break;
            case ProgrammingEnum::PROGRAMMING_COMMUNITY:  //社区网规
                $list = MapNationalCommunityModel::query()
                    ->leftJoin('customer_department_task', 'customer_department_task.wgNumber', '=', 'map_national_communities.wgNumber')
                    ->when(
                        ($isOwn || $statusArr) && $isKms, function ($query) use ($statusData, $statusArr, $isOwn, $userInfo) {
                        $query->when(
                            $isOwn && $userInfo, function ($query) use ($userInfo) {
                            $query->where('customer_department_task.assignId', $userInfo['userId'] ?? 0);//只看自己的
                        }
                        )->when(
                            $statusArr, function ($query) use ($statusData, $statusArr) {
                            $query->where(
                                function ($query) use ($statusData, $statusArr) {
                                    $query->when(
                                        $statusData, function ($query) use ($statusData) {
                                        $query->whereIn('customer_department_task.projectPhase', $statusData);//关联项目阶段状态
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && $statusData, function ($query) use ($statusArr) {
                                        $query->orWhere(
                                            function ($query) use ($statusArr) {
                                                $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                                ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                            }
                                        );
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && !$statusData, function ($query) use ($statusArr) {
                                        $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                        ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                    }
                                    );
                                }
                            );
                        }
                        );
                    }
                    )
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('map_national_communities.city', 'like', "%$city%");
                    })
                    ->when(
                        $provinceCodes, function ($query) use ($provinceCodes) {
                        $query->whereIn('map_national_communities.provinceCode', $provinceCodes);
                    }
                    )
                    ->when(
                        $cityCodes, function ($query) use ($cityCodes) {
                        $query->whereIn('map_national_communities.cityCode', $cityCodes);
                    }
                    )
                    ->when(
                        $districtCodes, function ($query) use ($districtCodes) {
                        $query->whereIn('map_national_communities.districtCode', $districtCodes);
                    }
                    )
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('map_national_communities.name', 'like', "%$name%");
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('map_national_communities.settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_communities.status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_communities.status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('map_national_communities.grade', $gradeArr);
                    })
                    ->select(['map_national_communities.status','map_national_communities.shopNum','map_national_communities.settle','customer_department_task.projectPhase'])
                    ->get();

                $totalCount = $list->count();
                if ($isKms) {
                    $clueTotal    = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE)->count(); // 有线索
                    $houseTotal   = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE)->count();// 有房源
                    $settledTotal = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM)->count();   // 已入驻
                } else {
                    $waitCount  = $list->where('status', ProgrammingEnum::STATUS_WAIT_EVALUATE)->count();
                    $passCount  = $list->where('status', '>=',  ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE)->count();
                    $enterCount = $list->where('status', '>=',  ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE)
                        ->where('shopNum', 0)
                        ->count();
                }
//                    ->each(function (MapNationalCommunityModel $mapNationalCommunityModel) use (&$settledTotal, &$houseTotal, &$clueTotal, &$totalCount, &$passCount, &$waitCount, &$enterCount) {
//                        $totalCount++;
//                        if ($mapNationalCommunityModel->status == ProgrammingEnum::STATUS_WAIT_EVALUATE) {
//                            $waitCount++;
//                        }
//                        if ($mapNationalCommunityModel->status >= ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE) {
//                            $passCount++;
//                        }
//                        if ($mapNationalCommunityModel->status >= ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE && $mapNationalCommunityModel->shopNum == 0) {
//                            $enterCount++;
//                        }
//                        $projectPhase = $mapNationalCommunityModel->projectPhase ?? 0;
//
//                        // 有线索
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE) {
//                            $clueTotal++;
//                        }
//
//                        // 有房源
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE) {
//                            $houseTotal++;
//                        }
//
//                        // 已入驻
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM) {
//                            $settledTotal++;
//                        }
//                    });
                break;
            case ProgrammingEnum::PROGRAMMING_TOWN:  //乡镇网规
                $list = MapTownshipPlanAreaModel::query()
                    ->leftJoin('customer_department_task', 'customer_department_task.wgNumber', '=', 'map_township_plan_area.wgNumber')
                    ->when(
                        ($isOwn || $statusArr) && $isKms, function ($query) use ($statusData, $statusArr, $isOwn, $userInfo) {
                        $query->when(
                            $isOwn && $userInfo, function ($query) use ($userInfo) {
                            $query->where('customer_department_task.assignId', $userInfo['userId'] ?? 0);//只看自己的
                        }
                        )->when(
                            $statusArr, function ($query) use ($statusData, $statusArr) {
                            $query->where(
                                function ($query) use ($statusData, $statusArr) {
                                    $query->when(
                                        $statusData, function ($query) use ($statusData) {
                                        $query->whereIn('customer_department_task.projectPhase', $statusData);//关联项目阶段状态
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && $statusData, function ($query) use ($statusArr) {
                                        $query->orWhere(
                                            function ($query) use ($statusArr) {
                                                $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                                ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                            }
                                        );
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && !$statusData, function ($query) use ($statusArr) {
                                        $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                        ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                    }
                                    );
                                }
                            );
                        }
                        );
                    }
                    )
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('map_township_plan_area.city', 'like', "%$city%");
                    })
                    ->when(
                        $provinceCodes, function ($query) use ($provinceCodes) {
                        $query->whereIn('map_township_plan_area.provinceCode', $provinceCodes);
                    }
                    )
                    ->when(
                        $cityCodes, function ($query) use ($cityCodes) {
                        $query->whereIn('map_township_plan_area.cityCode', $cityCodes);
                    }
                    )
                    ->when(
                        $districtCodes, function ($query) use ($districtCodes) {
                        $query->whereIn('map_township_plan_area.districtCode', $districtCodes);
                    }
                    )
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('map_township_plan_area.area', 'like', "%$name%");
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('map_township_plan_area.settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_township_plan_area.status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_township_plan_area.status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('map_township_plan_area.grade', $gradeArr);
                    })
                    ->when(mb_strlen($chosen), function ($query) use ($chosen) {
                        $chosenArr = explode(',', $chosen);
                        if (count($chosenArr) == 1) {
                            if ($chosen == 1) {
                                $query->where('map_township_plan_area.qianqiangTownRank', '!=', 0);
                            }
                            if ($chosen == 2) {
                                $query->where('map_township_plan_area.qianqiangTownRank', 0);
                            }
                        }
                    })
                    ->select(['map_township_plan_area.status','map_township_plan_area.shopNum','map_township_plan_area.settle','customer_department_task.projectPhase'])
                    ->get();

                $totalCount = $list->count();
                if ($isKms) {
                    $clueTotal    = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE)->count(); // 有线索
                    $houseTotal   = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE)->count();// 有房源
                    $settledTotal = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM)->count();   // 已入驻
                } else {
                    $waitCount  = $list->where('status', ProgrammingEnum::STATUS_WAIT_EVALUATE)->count();
                    $passCount  = $list->where('status', '>=',  ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE)->count();
                    $enterCount = $list->where('status', '>=',  ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE)
                        ->where('shopNum', 0)
                        ->count();
                }
//                    ->each(function (MapTownshipPlanAreaModel $mapTownshipPlanAreaModel) use (&$houseTotal, &$clueTotal, &$settledTotal, &$totalCount, &$passCount, &$waitCount, &$enterCount) {
//                        $totalCount++;
//                        if ($mapTownshipPlanAreaModel->status == ProgrammingEnum::STATUS_WAIT_EVALUATE) {
//                            $waitCount++;
//                        }
//                        if ($mapTownshipPlanAreaModel->status >= ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE) {
//                            $passCount++;
//                        }
//                        if ($mapTownshipPlanAreaModel->status >= ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE && $mapTownshipPlanAreaModel->shopNum == 0) {
//                            $enterCount++;
//                        }
//                        $projectPhase = $mapTownshipPlanAreaModel->projectPhase ?? 0;
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE) {
//                            $clueTotal++;// 有线索
//                        }
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE) {
//                            $houseTotal++;// 有房源
//                        }
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM) {
//                            $settledTotal++;// 已入驻
//                        }
//                    });
                break;
            case ProgrammingEnum::PROGRAMMING_SCHOOL:  //学校网规
                $list = MapNationalUniversitiesModel::query()
                    ->leftJoin('customer_department_task', 'customer_department_task.wgNumber', '=', 'map_national_universities.wgNumber')
                    ->when(
                        ($isOwn || $statusArr) && $isKms, function ($query) use ($statusData, $statusArr, $isOwn, $userInfo) {
                        $query->when(
                            $isOwn && $userInfo, function ($query) use ($userInfo) {
                            $query->where('customer_department_task.assignId', $userInfo['userId'] ?? 0);//只看自己的
                        }
                        )->when(
                            $statusArr, function ($query) use ($statusData, $statusArr) {
                            $query->where(
                                function ($query) use ($statusData, $statusArr) {
                                    $query->when(
                                        $statusData, function ($query) use ($statusData) {
                                        $query->whereIn('customer_department_task.projectPhase', $statusData);//关联项目阶段状态
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && $statusData, function ($query) use ($statusArr) {
                                        $query->orWhere(
                                            function ($query) use ($statusArr) {
                                                $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                                ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                            }
                                        );
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && !$statusData, function ($query) use ($statusArr) {
                                        $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                        ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                    }
                                    );
                                }
                            );
                        }
                        );
                    }
                    )
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('map_national_universities.city', 'like', "%$city%");
                    })
                    ->when(
                        $provinceCodes, function ($query) use ($provinceCodes) {
                        $query->whereIn('map_national_universities.provinceCode', $provinceCodes);
                    }
                    )
                    ->when(
                        $cityCodes, function ($query) use ($cityCodes) {
                        $query->whereIn('map_national_universities.cityCode', $cityCodes);
                    }
                    )
                    ->when(
                        $districtCodes, function ($query) use ($districtCodes) {
                        $query->whereIn('map_national_universities.districtCode', $districtCodes);
                    }
                    )
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('map_national_universities.name', 'like', "%$name%");
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('map_national_universities.settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_universities.status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_universities.status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('map_national_universities.grade', $gradeArr);
                    })
                    ->when(mb_strlen($chosen), function ($query) use ($chosen) {
                        $chosenArr = explode(',', $chosen);
                        if (in_array(1, $chosenArr)) {
                            $query->where('map_national_universities.project985', '是');
                        }
                        if (in_array(2, $chosenArr)) {
                            $query->where('map_national_universities.project211', '是');
                        }
                        if (in_array(3, $chosenArr)) {
                            $query->where('map_national_universities.strongBasis', '是');
                        }
                        if (in_array(4, $chosenArr)) {
                            $query->where('map_national_universities.doubleFirstClass', '是');
                        }
                    })
                    ->select(['map_national_universities.status','map_national_universities.shopNum','map_national_universities.settle','customer_department_task.projectPhase'])
                    ->get();

                $totalCount = $list->count();
                if ($isKms) {
                    $clueTotal    = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE)->count(); // 有线索
                    $houseTotal   = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE)->count();// 有房源
                    $settledTotal = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM)->count();   // 已入驻
                } else {
                    $waitCount  = $list->where('status', ProgrammingEnum::STATUS_WAIT_EVALUATE)->count();
                    $passCount  = $list->where('status', '>=',  ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE)->count();
                    $enterCount = $list->where('status', '>=',  ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE)
                        ->where('shopNum', 0)
                        ->count();
                }
//                    ->each(function (MapNationalUniversitiesModel $mapNationalUniversitiesModel) use (&$houseTotal, &$clueTotal, &$settledTotal, &$totalCount, &$passCount, &$waitCount, &$enterCount) {
//                        $totalCount++;
//                        if ($mapNationalUniversitiesModel->status == ProgrammingEnum::STATUS_WAIT_EVALUATE) {
//                            $waitCount++;
//                        }
//                        if ($mapNationalUniversitiesModel->status >= ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE) {
//                            $passCount++;
//                        }
//                        if ($mapNationalUniversitiesModel->status >= ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE && $mapNationalUniversitiesModel->shopNum == 0) {
//                            $enterCount++;
//                        }
//                        $projectPhase = $mapNationalUniversitiesModel->projectPhase ?? 0;
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE) {
//                            $clueTotal++;// 有线索
//                        }
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE) {
//                            $houseTotal++;// 有房源
//                        }
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM) {
//                            $settledTotal++;// 已入驻
//                        }
//                    });
                break;
            case ProgrammingEnum::PROGRAMMING_INDUSTRIAL_PARKS:  //产业园区网规
                $list = MapNationalIndustrialParkModel::query()
                    ->leftJoin('customer_department_task', 'customer_department_task.wgNumber', '=', 'map_national_industrial_park.wgNumber')
                    ->when(
                        ($isOwn || $statusArr) && $isKms, function ($query) use ($statusData, $statusArr, $isOwn, $userInfo) {
                        $query->when(
                            $isOwn && $userInfo, function ($query) use ($userInfo) {
                            $query->where('customer_department_task.assignId', $userInfo['userId'] ?? 0);//只看自己的
                        }
                        )->when(
                            $statusArr, function ($query) use ($statusData, $statusArr) {
                            $query->where(
                                function ($query) use ($statusData, $statusArr) {
                                    $query->when(
                                        $statusData, function ($query) use ($statusData) {
                                        $query->whereIn('customer_department_task.projectPhase', $statusData);//关联项目阶段状态
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && $statusData, function ($query) use ($statusArr) {
                                        $query->orWhere(
                                            function ($query) use ($statusArr) {
                                                $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                                ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                            }
                                        );
                                    }
                                    )->when(
                                        in_array(ProgrammingEnum::WG_STATUS_1, $statusArr) && !$statusData, function ($query) use ($statusArr) {
                                        $query->where('customer_department_task.manageStatus', CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN)//未指派
                                        ->orWhereRaw('customer_department_task.id is null');//未关联勘址
                                    }
                                    );
                                }
                            );
                        }
                        );
                    }
                    )
                    ->when(mb_strlen($city), function ($query) use ($city) {
                        $query->where('map_national_industrial_park.city', 'like', "%$city%");
                    })
                    ->when(
                        $provinceCodes, function ($query) use ($provinceCodes) {
                        $query->whereIn('map_national_industrial_park.provinceCode', $provinceCodes);
                    }
                    )
                    ->when(
                        $cityCodes, function ($query) use ($cityCodes) {
                        $query->whereIn('map_national_industrial_park.cityCode', $cityCodes);
                    }
                    )
                    ->when(
                        $districtCodes, function ($query) use ($districtCodes) {
                        $query->whereIn('map_national_industrial_park.districtCode', $districtCodes);
                    }
                    )
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('map_national_industrial_park.name', 'like', "%$name%");
                    })
                    ->when(mb_strlen($settleStatus), function ($query) use ($settleStatus) {
                        $query->where('map_national_industrial_park.settle', $settleStatus);
                    })
                    ->when(mb_strlen($status), function ($query) use ($status) {
                        $statusArr = explode(',', $status);
                        if (in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_industrial_park.status', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        } elseif (!in_array(ProgrammingEnum::STATUS_WAIT_EVALUATE, $statusArr) && count($statusArr) == 1) {
                            $query->where('map_national_industrial_park.status', '>', ProgrammingEnum::STATUS_WAIT_EVALUATE);
                        }
                    })
                    ->when(mb_strlen($grade), function ($query) use ($grade) {
                        $gradeArr = explode(',', $grade);
                        $query->whereIn('map_national_industrial_park.grade', $gradeArr);
                    })
                    ->select(['map_national_industrial_park.status','map_national_industrial_park.shopNum','map_national_industrial_park.settle','customer_department_task.projectPhase'])
                    ->get();

                $totalCount = $list->count();
                if ($isKms) {
                    $clueTotal    = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE)->count(); // 有线索
                    $houseTotal   = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE)->count();// 有房源
                    $settledTotal = $list->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM)->count();   // 已入驻
                } else {
                    $waitCount  = $list->where('status', ProgrammingEnum::STATUS_WAIT_EVALUATE)->count();
                    $passCount  = $list->where('status', '>=', ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE)->count();
                    $enterCount = $list->where('status', '>=',  ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE)
                        ->where('shopNum', 0)
                        ->count();
                }
//                    ->each(function (MapNationalIndustrialParkModel $mapNationalIndustrialParkModel) use (&$houseTotal, &$clueTotal, &$settledTotal, &$totalCount, &$passCount, &$waitCount, &$enterCount) {
//                        $totalCount++;
//                        if ($mapNationalIndustrialParkModel->status == ProgrammingEnum::STATUS_WAIT_EVALUATE) {
//                            $waitCount++;
//                        }
//                        if ($mapNationalIndustrialParkModel->status >= ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE) {
//                            $passCount++;
//                        }
//                        if ($mapNationalIndustrialParkModel->status >= ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE && $mapNationalIndustrialParkModel->shopNum == 0) {
//                            $enterCount++;
//                        }
//                        $projectPhase = $mapNationalIndustrialParkModel->projectPhase ?? 0;
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE) {
//                            $clueTotal++;// 有线索
//                        }
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE) {
//                            $houseTotal++;// 有房源
//                        }
//                        if ($projectPhase == CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM) {
//                            $settledTotal++;// 已入驻
//                        }
//                    });
                break;
            default:
                self::throwErr('网规类型错误');
        }

        if ($isKms) {
            return compact(
                'totalCount',
                'clueTotal',
                'houseTotal',
                'settledTotal'
            );
        }
        return compact(
            'totalCount',
            'passCount',
            'waitCount',
            'enterCount'
        );
    }

    public static function sift($city, $isKms = false)
    {
        $districts = [];
        if (mb_strlen($city) && !$isKms) {
            $key     = WangGuiCityByPower::getRandomAmapKey();
            $areaRes = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
                ->get(config('area.getAreaByName'), [
                    'keywords'    => $city,
                    'subdistrict' => 1,
                    'key'         => $key,
                ])
                ->json();
            if ($areaRes['status'] == 1 && count($areaRes['districts'])) {
                foreach ($areaRes['districts'] as $city) {
                    if ($city['level'] != 'city') {
                        continue;
                    }
                    foreach ($city['districts'] as $district) {
                        $districts[] = $district['name'];
                    }
                }
            }
        }


        $sift                          = [];
        $sift[0]['district']['name']   = '区域';
        $sift[0]['district']['input']  = 'radio';
        $sift[0]['district']['key']    = 'district';
        $sift[0]['district']['select'] = collect($districts)->map(function ($value) {
            return [
                'name'  => $value,
                'value' => $value,
            ];
        })->values()->toArray();
        $chosen                        = [];
        $sift[1]['sort']['name']       = '排序';
        $sift[1]['sort']['input']      = 'radio';
        $sift[1]['sort']['key']        = 'sort';
        $sift[1]['sort']['select']     = collect(ProgrammingEnum::MALL_SORT_MAPPING)->map(function ($mallSort, $value) {
            return [
                'name'  => $mallSort,
                'value' => $value,
            ];
        })->values()->toArray();
        $chosen[1]['other']['name']    = '入选榜单';
        $chosen[1]['other']['key']     = 'chosen';
        $chosen[1]['other']['input']   = 'checkout';
        $chosen[1]['other']['select']  = [
            [
                'name'  => '已入选',
                'value' => 1
            ],
            [
                'name'  => '未入选',
                'value' => 2
            ]
        ];
        $sift[2]['sort']['name']       = '排序';
        $sift[2]['sort']['input']      = 'radio';
        $sift[2]['sort']['key']        = 'sort';
        $sift[2]['sort']['select']     = collect(ProgrammingEnum::STREET_SORT_MAPPING)->map(function ($mallSort, $value) {
            return [
                'name'  => $mallSort,
                'value' => $value,
            ];
        })->values()->toArray();
        $sift[3]['sort']['name']       = '排序';
        $sift[3]['sort']['input']      = 'radio';
        $sift[3]['sort']['key']        = 'sort';
        $sift[3]['sort']['select']     = collect(ProgrammingEnum::TOWN_SORT_MAPPING)->map(function ($mallSort, $value) {
            return [
                'name'  => $mallSort,
                'value' => $value,
            ];
        })->values()->toArray();
        $chosen[3]['other']['name']    = '千强镇';
        $chosen[3]['other']['key']     = 'chosen';
        $chosen[3]['other']['input']   = 'checkout';
        $chosen[3]['other']['select']  = [
            [
                'name'  => '是千强镇',
                'value' => 1
            ],
            [
                'name'  => '不是千强镇',
                'value' => 2
            ]
        ];
        $sift[4]['sort']['name']       = '排序';
        $sift[4]['sort']['input']      = 'radio';
        $sift[4]['sort']['key']        = 'sort';
        $sift[4]['sort']['select']     = collect(ProgrammingEnum::SCHOOL_SORT_MAPPING)->map(function ($mallSort, $value) {
            return [
                'name'  => $mallSort,
                'value' => $value,
            ];
        })->values()->toArray();
        $chosen[4]['other']['name']    = '高校类型';
        $chosen[4]['other']['key']     = 'chosen';
        $chosen[4]['other']['input']   = 'checkout';
        $chosen[4]['other']['select']  = [
            [
                'name'  => '985',
                'value' => 1
            ],
            [
                'name'  => '211',
                'value' => 2
            ],
            [
                'name'  => '强基',
                'value' => 3
            ],
            [
                'name'  => '双一流',
                'value' => 4
            ]
        ];
        $sift[5]['sort']['name']       = '排序';
        $sift[5]['sort']['input']      = 'radio';
        $sift[5]['sort']['key']        = 'sort';
        $sift[5]['sort']['select']     = collect(ProgrammingEnum::PARK_SORT_MAPPING)->map(function ($mallSort, $value) {
            return [
                'name'  => $mallSort,
                'value' => $value,
            ];
        })->values()->toArray();

        $sift[6]['sort']['name']       = '排序';
        $sift[6]['sort']['input']      = 'radio';
        $sift[6]['sort']['key']        = 'sort';
        $sift[6]['sort']['select']     = collect(ProgrammingEnum::STREET_SORT_MAPPING)->map(function ($mallSort, $value) {
            return [
                'name'  => $mallSort,
                'value' => $value,
            ];
        })->values()->toArray();


        $sift['status']['name']   = '状态';
        $sift['status']['key']    = 'status';
        $sift['status']['input']  = 'children';
        $sift['status']['select'] = $isKms ? collect(ProgrammingEnum::WG_STATUS_MAPPING)->map(
            function ($status, $value) {
                return [
                    'name'  => $status,
                    'value' => $value,
                ];
            }
        )->values()->toArray()
            :[
            [
                'name'   => '评估状态',
                'key'    => 'status',
                'input'  => 'checkout',
                'select' => collect(ProgrammingEnum::STATUS_SCORE_SIFT_MAPPING)->map(function ($status, $value) {
                    return [
                        'name'  => $status,
                        'value' => $value,
                    ];
                })->values()->toArray(),
            ], [
                'name'     => '可开潜力评分',
                'key'      => 'openScore',
                'input'    => 'axis',
                'min'      => 0,
                'max'      => 5,
                'interval' => 0.5,
                'select'   => collect(ProgrammingEnum::WANGGUI_SOURCE_MAPPING)->map(function ($status, $value) {
                    return [
                        'name'  => $status,
                        'value' => implode(',', ProgrammingEnum::WANGGUI_SOURCE_SECTION_MAPPING[$value]),
                        'min'   => ProgrammingEnum::WANGGUI_SOURCE_SECTION_MAPPING[$value][0],
                        'max'   => ProgrammingEnum::WANGGUI_SOURCE_SECTION_MAPPING[$value][1],
                    ];
                })->values()->toArray()
            ], [
                'name'   => '入驻状态',
                'key'    => 'settleStatus',
                'input'  => 'checkout',
                'select' => collect(ProgrammingEnum::SETTLE_STATUS_MAPPING_STATUS)->map(function ($status, $value) {
                    return [
                        'name'  => $status,
                        'value' => $value,
                    ];
                })->values()->toArray(),
            ]
        ];


        $sift['grade']['name']   = '等级';
        $sift['grade']['key']    = 'grade';
        $sift['grade']['input']  = 'checkout';
        $sift['grade']['select'] = collect(ProgrammingEnum::GRADE_MAPPING)->map(function ($grade, $value) {
            return [
                'name'  => $grade,
                'value' => $value,
            ];
        })->values()->toArray();

        return [
            '1' => array_merge($sift[0], $sift[1], ['status' => $sift['status']], ['more' => ['name' => '更多', 'input' => 'children', 'select' => [$sift['grade'], array_values($chosen[1])[0]]]]),
            '2' => array_merge($sift[0], $sift[2], ['status' => $sift['status']], ['more' => ['name' => '更多', 'input' => 'children', 'select' => [$sift['grade']]]]),
            '3' => array_merge($sift[0], $sift[3], ['status' => $sift['status']], ['more' => ['name' => '更多', 'input' => 'children', 'select' => [$sift['grade'], array_values($chosen[3])[0]]]]),
            '4' => array_merge($sift[0], $sift[4], ['status' => $sift['status']], ['more' => ['name' => '更多', 'input' => 'children', 'select' => [$sift['grade'], array_values($chosen[4])[0]]]]),
            '5' => array_merge($sift[0], $sift[5], ['status' => $sift['status']], ['more' => ['name' => '更多', 'input' => 'children', 'select' => [$sift['grade']]]]),
            '6' => array_merge($sift[0], $sift[6], ['status' => $sift['status']], ['more' => ['name' => '更多', 'input' => 'children', 'select' => [$sift['grade']]]]),
        ];
    }

    public static function hotCity()
    {
        return ConfigService::config('wanggui', 'hotCity');
    }

    public static function cityListByPower($haveCity)
    {
        $data        = [];
        $hotCityList = ConfigService::config('wanggui', 'hotCity');
        $newHotCity  = [];
        collect($haveCity)->each(function ($cityName) use (&$data, $hotCityList, &$newHotCity) {
            $filterCity = mb_substr($cityName, 0, 2);
            if (in_array($filterCity, $hotCityList['hotCity'])) {
                $newHotCity[] = $filterCity;
            }
            if (mb_substr($cityName, -1) == '市') {
                $cityName = mb_substr($cityName, 0, (mb_strlen($cityName) - 1));
            }
            $key                      = Cache::rememberForever('tiger:openShop:wanggui:city:pinyin:' . $cityName, function () use ($cityName) {
                return strtoupper(mb_substr((new Pinyin())->permalink($cityName), 0, 1));
            });
            $data['cityList'][$key][] = str_replace('城区', '', $cityName);
        });
        $data['hotCityList'] = array_values(array_intersect($hotCityList['hotCity'], $newHotCity));
        ksort($data['cityList']);
        return $data;
    }

    public static function getCityByLatLng($haveCity, $lat, $lng)
    {
        if (!count($haveCity)) {
            self::throwErr('暂未获得城市列表，请联系相关负责人');
        }
        $key        = WangGuiCityByPower::getRandomAmapKey();
        $chooseCity = '';
        $areaRes    = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
            ->get(config('area.geocodeRegeo'), [
                'key'      => $key,
                'location' => $lng . ',' . $lat,
            ])
            ->json();
        if ($areaRes['status'] == 1 && isset($areaRes['regeocode']['addressComponent']['city'])) {
            $oldCity    = $areaRes['regeocode']['addressComponent']['city'] == [] ? $areaRes['regeocode']['addressComponent']['province'] : $areaRes['regeocode']['addressComponent']['city'];
            if (is_array($oldCity)) {
                $chooseCity = '#';
            } else {
                $chooseCity = mb_substr($oldCity, 0, 2);
            }
        }
        $power = false;
        foreach ($haveCity as $value) {
            if (mb_strpos($value, $chooseCity) !== false) {
                $power = true;
                break;
            }
        }

        if (!$power) {
            $chooseCity = $haveCity[0];
        }
        return [
            'chooseCity' => $chooseCity
        ];
    }

    //模糊匹配城市算法
    public static function blurMatchCity($city): string
    {
        if(!mb_strlen($city)){
            return '';
        }
        if (mb_strpos($city, '城区') !== false) {
            $city = mb_substr($city, 0, mb_strpos($city, '城区'));
        }
        if (mb_strlen($city) > 2) {

            return mb_substr($city, 0, (mb_strlen($city) - 1));
        } else {
            return $city;
        }
    }


    /**
     * 获得评估详情
     * @param $id
     * @param $rmsUserId
     * @return array
     * @throws GuzzleException
     */
    public static function evaluateDetail($id, $rmsUserId): array
    {
        $logModel = OpenShopSiteLocationExamineLogModel::query()
            ->where('id', $id)
            ->with(['resourceRelByWanggui', 'wangguiSiteDistrictRel.resourceRel'])
            ->first();

        if (null == $logModel) {
            self::throwErr('评估详情不存在');
        }
        $isUpdate = false;

        if ($rmsUserId == $logModel->createdByUid) {
            $isUpdate = true;
        }

        $body      = RmsUserService::getRmsUserInfoByUserIds([$logModel->createdByUid])['data'] ?? [];
        $userNames = array_column($body, 'username', 'id');
        $fileArr   = [];
        $logModel->resourceRelByWanggui->each(function (ResourcesModel $resourcesModel) use (&$fileArr) {
            $fileArr[$resourcesModel->name][] = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
        });
        $openDistrict = [];
        $logModel->wangguiSiteDistrictRel->each(function (WangguiSiteDistrictModel $wangguiSiteDistrictModel) use (&$openDistrict) {

            $openDistrictFile = [];
            $wangguiSiteDistrictModel->resourceRel->each(function (ResourcesModel $resourcesModel) use (&$openDistrictFile) {
                $openDistrictFile[] = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
            });

            $openDistrict[] = [
                'id'              => $wangguiSiteDistrictModel->id,
                'name'            => $wangguiSiteDistrictModel->name,
                'isEmptyShop'     => $wangguiSiteDistrictModel->isEmptyShop,
                'isEmptyShopText' => WangguiSiteDistrictModel::IS_EMPTY_SHOP_MAPPING[$wangguiSiteDistrictModel->isEmptyShop] ?? '',
                'file'            => $openDistrictFile
            ];
        });


        return array_merge([
            'id'                 => $logModel->id,
            'username'           => $userNames[$logModel->createdByUid] ?? '-',
            'openPotential'      => $logModel->openPotential,
            'flowOfPeopleScores' => $logModel->flowOfPeopleScores,
            'passengerFlowDrive' => $logModel->passengerFlowDrive ? explode(',', $logModel->passengerFlowDrive) : [],
            'customerGroupType'  => $logModel->customerGroupType ? explode(',', $logModel->customerGroupType) : [],
            'statusText'         => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$logModel->openPotential] ?? '-',
            'createdAt'          => $logModel->createdAt->format('Y-m-d H:i'),
            'evaluateTime'       => $logModel->updatedAt->format('Y-m-d H:i'),
            'content'            => $logModel->content,
            'weekDay'            => DateTool::cnWeekOfDay($logModel->updatedAt->dayOfWeek),
            'weather'            => json_decode($logModel->extra, true)['weather'] ?? '-',
            'openDistrictList'   => $openDistrict,
            'isUpdate'           => $isUpdate,
            'isDelete'           => false,
        ], $fileArr);
    }

    public static function browsingHistory($rmsUserId, int $pageNum, int $pageSize, string $name)
    {
        //首先获得每页的type和id
        $paginator = WangguiBrowsingHistoryModel::query()
            ->when(mb_strlen($name), function ($query) use ($name) {
                $query->where('wgName', 'like', "%$name%");
            })
            ->where('createdByUid', $rmsUserId)
            ->orderByDesc('updatedAt')
            ->paginate($pageSize, ['*'], 'page', $pageNum);
        //数组处理  获得每个类型下面的ID
        $tempTypeList = [];
        $tempSort     = [];
        $paginator->each(function (WangguiBrowsingHistoryModel $browsingHistoryModel) use (&$tempTypeList, &$tempSort) {
            $tempSort[$browsingHistoryModel->wgNumber]   = $browsingHistoryModel->updatedAt->toDateTimeString();
            $tempTypeList[$browsingHistoryModel->type][] = $browsingHistoryModel->businessId;
        });
        $list = [];
        foreach ($tempTypeList as $key => $ids) {
            $list = array_merge($list, array_column(self::list($key, ProgrammingEnum::SUB_TYPE_DEFAULT, '', '', '', '', 1, 10, '', '', '', '', '', '', '', $ids)[0], null, 'wgNumber'));
        }
        //$tempList = array_column(array_merge(...$list), null, 'wgNumber');
        $data = [];
        foreach (array_keys($tempSort) as $value) {
            if (!isset($list[$value])) {
                continue;
            }
            $list[$value]['dateTime'] = $tempSort[$value];
            $data[]                   = $list[$value];
        }
        return [
            'count'    => $paginator->total(),
            'list'     => $data,
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
        ];
    }

    public static function evaluateHistory($rmsUserId, int $pageNum, int $pageSize, string $name)
    {
        //首先获得每页的type和id
        $paginator    = OpenShopSiteLocationExamineLogModel::query()
            ->where('source', OpenShopSiteLocationExamineLogModel::SOURCE_WG_AUDIT)
            ->where('isToStore', OpenShopSiteLocationExamineLogModel::IS_NEW_YES)
            ->where('createdByUid', $rmsUserId)
            ->when(mb_strlen($name), function ($query) use ($name) {
                $query->where('extra', 'like', "%$name%");
            })
            ->orderByDesc('updatedAt')
            ->paginate($pageSize, ['*'], 'page', $pageNum);
        $tempSort     = [];
        $tempStatus   = [];
        $tempTypeList = [];
        $paginator->each(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use (&$tempTypeList, &$tempSort, &$tempStatus) {
            $tempSort[$locationExamineLogModel->orderNo]    = $locationExamineLogModel->updatedAt->toDateTimeString();
            $tempStatus[$locationExamineLogModel->orderNo]  = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-';
            $tempTypeList[$locationExamineLogModel->type][] = $locationExamineLogModel->orderNo;
        });
        $list = [];
        foreach ($tempTypeList as $key => $orderNoArr) {
            $list = array_merge($list, array_column(self::list($key, ProgrammingEnum::SUB_TYPE_DEFAULT, '', '', '', '', 1, 10, '', '', '', '', '', '', '', [], $orderNoArr)[0], null, 'wgNumber'));
        }
        $data = [];
        foreach (array_keys($tempSort) as $value) {
            if (!isset($list[$value])) {
                continue;
            }
            $list[$value]['dateTime']   = $tempSort[$value];
            $list[$value]['statusText'] = $tempStatus[$value];
            $data[]                     = $list[$value];
        }
        return [
            'count'    => $paginator->total(),
            'list'     => $data,
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
        ];
    }

    public static function importStreet(string $name, string $url)
    {
        $streetGeoJsonFilesArr  = [];
        $streetGeoJsonFilesJson = ConfigModel::query()
            ->where('module', ConfigModel::MODULE_WANGGUI)
            ->where('name', ConfigModel::NAME_STREET_GEO_JSON)
            ->value('value');
        if ($streetGeoJsonFilesJson) {
            $streetGeoJsonFilesArr = json_decode($streetGeoJsonFilesJson, true);
        }

        $haveKeyTodayNum = [];
        $date            = Carbon::now()->toDateString();
        foreach ($streetGeoJsonFilesArr as $key => $streetGeoJsonFiles) {
            if (strpos($key, $date)) {
                $haveKeyTodayNum[] = (int)$key;
            }
        }

        if (count($haveKeyTodayNum)) {
            $setUpKey = max($haveKeyTodayNum) + 1 . ':' . $date;
        } else {
            $setUpKey = '1:' . $date;
        }
        $temp = [
            $setUpKey => [
                [
                    'name' => $name,
                    'url'  => $url
                ]
            ],
        ];

        ConfigModel::query()
            ->where('module', ConfigModel::MODULE_WANGGUI)
            ->where('name', ConfigModel::NAME_STREET_GEO_JSON)
            ->update([
                'value' => json_encode(array_merge($temp, $streetGeoJsonFilesArr), JSON_UNESCAPED_UNICODE)
            ]);
        ob_start();
        Artisan::call('wanggui:import-street-data');
        ob_clean();
    }


    public static function getFeishuImageKey($url)
    {
        //飞书默认照片
        $imageKey = 'img_v2_041b28e3-5680-48c2-9af2-497ace79333g';
        //上传图片用于飞书通知展示
        try {
            $imageKey = \App\Service\OpenShop\Feishu\BaseService::uploadFeishuImage(UserPermissionAuth::MODULE_OPEN_SITE, $url, 0) ?: '';
        } catch (\Exception $exception) {

        }

        return $imageKey;

    }

    public static function joinUploadTranscoding($businessId, $module, $business, $name, $type, $url, $isPublic, $userId)
    {
        $resourceId = ResourcesModel::query()->create([
            'businessId'   => $businessId,
            'module'       => $module,
            'business'     => $business,
            'name'         => $name,
            'url'          => ltrim(parse_url($url, PHP_URL_PATH), '/'),
            'extra'        => json_encode(['type' => $type], JSON_UNESCAPED_UNICODE),
            'isPublic'     => $isPublic,
            'createdByUid' => $userId,
            'updatedByUid' => $userId,
        ])->id;

        $jobId                                 = UploadTranscoding::asyncFileTranscoding(ltrim(parse_url($url, PHP_URL_PATH), '/'), config('file-transcoding.kf-file'), '');
        $fileTranscodingModel                  = new FileTranscodingJobModel();
        $fileTranscodingModel->jobId           = $jobId;
        $fileTranscodingModel->model           = ResourcesModel::class;
        $fileTranscodingModel->filePath        = ltrim(parse_url($url, PHP_URL_PATH), '/');
        $fileTranscodingModel->updatedField    = 'url';
        $fileTranscodingModel->updatedModelId  = $resourceId;
        $fileTranscodingModel->filePathEncoded = substr(ltrim(parse_url($url, PHP_URL_PATH), '/'), 0, strrpos(ltrim(parse_url($url, PHP_URL_PATH), '/'), '.')) . '_encoded.mp4';
        $fileTranscodingModel->status          = FileTranscodingJobModel::STATUS_WAIT;
        $fileTranscodingModel->save();
    }

    public static function combineArrays($a, $b)
    {
        $newArray = [];
        $countB   = count($b);

        $countA = intval($countB / 3);

        foreach ($a as $key => $value) {
            if ($key == "element") {
                for ($i = 0; $i < 3; $i++) {
                    $newArray[] = $b[$i] ?? array();
                }
            } elseif (is_array($value)) {
                $newArray[] = $countA > 0 ? self::combineArrays($value, array_slice($b, 3, count($b))) : $value;
                $countA--;
            } else {
                $newArray[] = $value;
            }
        }

        return $newArray;
    }

    /**
     * 点位状态勘址状态转化
     * @param $projectPhase
     * @return array
     */
    public static function conversionStatus($projectPhase): array
    {
        $status = ProgrammingEnum::WG_STATUS_1;
        switch ($projectPhase) {
            case CustomerDepartmentTaskModel::PROJECT_PHASE_WAIT_FOLLOW_UP:
            case CustomerDepartmentTaskModel::PROJECT_PHASE_NO_CLUE:
                $status = ProgrammingEnum::WG_STATUS_2;
                break;
            case CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE:
                $status = ProgrammingEnum::WG_STATUS_3;
                break;
            case CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE:
                $status = ProgrammingEnum::WG_STATUS_4;
                break;
            case CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_LOCATION:
                $status = ProgrammingEnum::WG_STATUS_5;
                break;
            case CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM:
                $status = ProgrammingEnum::WG_STATUS_6;
                break;
        }
        return ['status' => $status, 'statusText' => ProgrammingEnum::WG_STATUS_MAPPING[$status] ?? ''];
    }
}
